使用python保存脚本中编辑的JPG图像



参考这个问题的答案,我尝试保存我自己的JPG图像文件,经过一些基本的图像处理。我只施加了旋转和剪切。这是我的代码:

        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)

我知道图像处理很好,因为如果我在保存之前显示它,它只是原始图像,如预期的那样有一点旋转和剪切。但我在保存它的时候做错了什么。我尝试没有astype(np.uint8))部分,但得到了一个错误。然后我从上面提到的链接中删除了一些代码,因为我猜这是专门用于傅里叶变换的,因为当我包含了它们的一些代码时,我得到了一个全灰色的图像,但是在我应用剪切的方向上有白线。但是现在保存的图像只有2KB,只有黑色。

当我尝试一些简单的事情:

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

然后我得到了这个错误:

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

我真的不需要使用PIL,如果有另一种方法来简单地保存我的图像,我很好。

查看PIL fork Pillow,它并没有过时,您应该使用它。

根据您的操作系统,您可能需要一些其他库来正确编译具有JPEG支持的PIL,请参阅此处

这可能也有帮助,说明你需要在保存之前将图像转换为RGB模式。

Image.open('old.jpeg').convert('RGB').save('new.jpeg')

最新更新