How to save image using PIL?

I just did some image processing using the Python Image Library (PIL), using the message I found earlier to perform Fourier transforms of images, and I can't get the save function to work. All the code works fine, but it just won’t save the resulting image:

from PIL import Image import numpy as np i = Image.open("C:/Users/User/Desktop/mesh.bmp") i = i.convert("L") a = np.asarray(i) b = np.abs(np.fft.rfft2(a)) j = Image.fromarray(b) j.save("C:/Users/User/Desktop/mesh_trans",".bmp") 

The error I am getting is the following:

 save_handler = SAVE[string.upper(format)] # unknown format KeyError: '.BMP' 

How to save image using Pythons PIL?

+45
python save python-imaging-library
Jan 22 '13 at 6:30
source share
4 answers

Error regarding the file extension, you use either bmp (without a dot), or pass the name of the output with the extension already. Now, to handle the error, you need to correctly change your data in the frequency domain to save as an integer image, PIL tells you that it does not accept floating point data to save as bmp.

Here is a suggestion (with other minor modifications, for example, using fftshift and numpy.array instead of numpy.asarray ) to perform the conversion for proper rendering:

 import sys import numpy from PIL import Image img = Image.open(sys.argv[1]).convert('L') im = numpy.array(img) fft_mag = numpy.abs(numpy.fft.fftshift(numpy.fft.fft2(im))) visual = numpy.log(fft_mag) visual = (visual - visual.min()) / (visual.max() - visual.min()) result = Image.fromarray((visual * 255).astype(numpy.uint8)) result.save('out.bmp') 
+58
Jan 23 '13 at 3:42
source share
β€” -

You should just let PIL get the file type from the extension, i.e. use:

 j.save("C:/Users/User/Desktop/mesh_trans.bmp") 
+17
Jan 22 '13 at 6:48
source share

Try to delete . to .bmp (it does not comply with BMP as expected). As you can see from the error, save_handler is the uppercase format that you provided, and then looks for a match in SAVE . However, the corresponding key in this BMP object (instead of .bmp ).

I don't know much about PIL , but because of the quick search around this seems like a problem with image mode . Change the definition of j to:

 j = Image.fromarray(b, mode='RGB') 

It seemed like I was working for me (however, note that I have little knowledge of PIL , so I would suggest using the @mmgp solution, since he / she knows clearly what they are doing :)). For mode types, I used this page - I hope one of the options there will work for you.

+3
Jan 22 '13 at 6:33
source share

I know this is old, but I found that opening a file with open(fp, 'w') and then saving the file would work. For example:

 j.save(open(fp, 'w')) 

fp is the path to the file, of course. (This is with a pillow)

+2
May 10 '17 at 14:46
source share



All Articles