使用python保存在脚本中编辑的JPG图像 [英] Using python to save a JPG image that was edited in the script

查看:282
本文介绍了使用python保存在脚本中编辑的JPG图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

我知道图像处理很好,因为如果在保存之前显示它,它就是原始图像,并且具有预期的旋转和剪切效果.但是保存时我做错了事.我试过没有astype(np.uint8))部分,但出现了错误.然后,我从上面提到的链接中删除了一些代码,因为我猜想它特别适用于傅立叶变换,因为当我包含它们的一些代码时,我得到的图像全是灰色的,但在剪切方向上有白线我申请了.但是现在保存下来的图像只有2KB,只有黑度.

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)

然后我收到此错误:

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

我真的不需要使用PIL,如果还有另一种方法可以简单地保存我的图像,那我很好.

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

推荐答案

查看PIL分支,

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

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

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

这也可能会帮助说保存之前需要将图像转换为RGB模式.

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')

这篇关于使用python保存在脚本中编辑的JPG图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆