python怎么编辑图片,使用python保存在脚本中编辑的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)

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.

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值