Using python to save a JPG image that was edited in the script
Asked Answered
S

1

0

Referring to the answer to this question, I tried to save my own JPG image files, after some basic image processing. I've only applied a rotation and a shear. This is my code:

        import numpy as np
        import sys
        from skimage import data, io, filter, color, exposure
        import skimage.transform as tf
        from skimage.transform import rotate, setup, AffineTransform
        from PIL import Image

        mypath = PATH_TO_FILENAME
        readfile = FILENAME
        img = color.rgb2gray(io.imread(mypath + readfile))
        myimg = rotate(img, angle=10, order=2)
        afine_tf = tf.AffineTransform(shear=0.1)
        editedimg = tf.warp(myimg, afine_tf)

        # IF I UNCOMMENT THE TWO LINES BELOW, I CAN SEE THE EDITED IMAGE AS EXPECTED
        #io.imshow(editedimg)
        #io.show()  

        saveimg= np.array(editedimg)
        result = Image.fromarray((saveimg).astype(np.uint8))
        newfile = "edited_" + readfile
        result.save(path+newfile)

I know that the image processing was fine because if I display it before saving, it's just the original image with a bit of rotation and shearing, as expected. But I'm doing something wrong while saving it. I tried without the astype(np.uint8)) part but got an error. Then I removed some of the code from the link mentioned above because I guessed it was particularly for Fourier Transforms, since when I included some of their code, then I got an image that was all gray but with white lines in the direction of the shear I'd applied. But now the image that gets saved is just 2KB of nothing but blackness.

And when I tried something as simple as:

result = Image.fromarray(editedimg)
result.save(path+newfile)

then I got this error:

 raise IOError("cannot write mode %s as JPEG" % im.mode)
IOError: cannot write mode F as JPEG

I don't really need to use PIL, if there's another way to simply save my image, I'm fine with that.

Spatial answered 17/6, 2014 at 14:8 Comment(0)
M
1

Look into the PIL fork, Pillow, is is not as outdated and what you should probably be using for this.

Also depending on your operating system you may need a few other libraries to compile PIL with JPEG support properly, see here

This may also help Says you need to convert your image to RGB mode before saving.

Image.open('old.jpeg').convert('RGB').save('new.jpeg')
Mahala answered 17/6, 2014 at 14:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.