Hi Mohit,
You may wish to ignore this suggestion: I often find that Caffe has features exposed in python that I'm not aware of that do things in a "friendlier" way than I usually use. So there may already be some feature there that is an easier way to do what you want that I don't know about.
But if you should be a C++ person I wrote a utility to do what you are doing (write an autoencoded output image to a file from my net), except that in my case the images are not 1-channel like in MNIST, but 3-channel color images. This is the utility here:
https://github.com/jyegerlehner/caffe/blob/nat_img_autoenc/tools/prop-patches.cppThe nice thing about it is that you just drop that cpp file into the caffe/tools/ directory, and then when you build caffe (at least with the cmake build; I don't use the makefile build), it will generate an executable called prop-patches. On the command line you give it the trained .caffemodel, the net's prototxt file, the input directory and output directory, and it runs all the images in the input directory through the net, and creates corresponding output images in the specified output directory. I don't know that it will work exactly as is for your use case since I use it for regular 3-channel RGB images, but perhaps it will since one would expect opencv can handle gray-scale or black and white images too.
There are some other utilities in that source directory too, that show reading from and writing to lmdb or leveldb databases to noise images and so forth.
Hope that's helpful.