PIL cannot write mode F to jpeg

JpegPython Imaging-LibraryFftModeIoerror

Jpeg Problem Overview


I am taking a jpg image and using numpy's fft2 to create/save a new image. However it throws this error

"IOError: cannot write mode F as JPEG" 

Is there an issue with CMYK and JPEG files in PIL???

p = Image.open('kibera.jpg')
bw_p = p.convert('L')
array_p = numpy.asarray(bw_p)
fft_p = abs(numpy.fft.rfft2(array_p))
new_p = Image.fromarray(fft_p)
new_p.save('kibera0.jpg')
new_p.histogram()

Jpeg Solutions


Solution 1 - Jpeg

Try convert the image to RGB:

...
new_p = Image.fromarray(fft_p)
if new_p.mode != 'RGB':
    new_p = new_p.convert('RGB')
...

Solution 2 - Jpeg

Semente's answer is right for color images For grayscale images you can use below:-

new_p = Image.fromarray(fft_p)
new_p = new_p.convert("L")

If you use new_p = new_p.convert('RGB') for a grayscale image then the image will still have 24 bit depth instead of 8 bit and would occupy thrice the size on hard disk and it wont be a true grayscale image.

Solution 3 - Jpeg

I think it may be that your fft_p array is in float type and the image should have every pixel in the format 0-255 (which is uint8), so maybe you can try doing this before creating the image from array:

fft_p = fft_p.astype(np.uint8)
new_p = Image.fromarray(fft_p)

But be aware that every element in the fft_p array should be in the 0-255 range, so maybe you would need to do some processing to that before to get the desired results, for example if you every element is a float between 0 and 1 you can multiply them by 255.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJHHPView Question on Stackoverflow
Solution 1 - JpegsementeView Answer on Stackoverflow
Solution 2 - JpegHimanshu PunethaView Answer on Stackoverflow
Solution 3 - Jpegxhenryx14View Answer on Stackoverflow