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

2024-10-01 15:32:52 发布

您现在位置:Python中文网/ 问答频道 /正文

参考this question的答案,我尝试在一些基本的图像处理之后保存自己的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,只有黑色。在

当我试着做一些简单的事情:

^{pr2}$

然后我得到了一个错误:

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

我真的不需要使用PIL,如果有其他方法可以简单地保存我的图像,我很乐意。在


Tags: 代码fromio图像importmodetfas
1条回答
网友
1楼 · 发布于 2024-10-01 15:32:52

看看PIL fork,Pillow,它并没有过时,您可能应该使用它来实现这一点。在

另外,根据您的操作系统,您可能需要一些其他库来编译具有JPEG支持的PIL,see here

This may also help表示在保存之前需要将图像转换为RGB模式。在

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

相关问题 更多 >

    热门问题