Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save an image with PIL?

I have just done some image processing using the Python image library (PIL) using a post I found earlier to perform fourier transforms of images and I can't get the save function to work. The whole code works fine but it just wont 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 get is the following:

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

How can I save an image with Pythons PIL?

like image 869
user1999274 Avatar asked Jan 22 '13 06:01

user1999274


People also ask

How do I save a picture from PIL?

save() Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. Keyword options can be used to provide additional instructions to the writer.

How do I save an image object in Python?

The PIL module is used for storing, processing, and displaying images in Python. To save images, we can use the PIL. save() function. This function is used to export an image to an external file.


2 Answers

The error regarding the file extension has been handled, you either use BMP (without the dot) or pass the output name with the extension already. Now to handle the error you need to properly modify your data in the frequency domain to be saved as an integer image, PIL is telling you that it doesn't accept float data to save as BMP.

Here is a suggestion (with other minor modifications, like using fftshift and numpy.array instead of numpy.asarray) for doing the conversion for proper visualization:

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') 
like image 53
mmgp Avatar answered Sep 17 '22 03:09

mmgp


You should be able to simply let PIL get the filetype from extension, i.e. use:

j.save("C:/Users/User/Desktop/mesh_trans.bmp") 
like image 27
wim Avatar answered Sep 21 '22 03:09

wim