Python - 更改像素值

时间:2014-07-13 21:40:18

标签: python

我已使用此代码更改图像的像素值

im=Image.open("image.jpg")
pix=im.load()
pix[50,50]=(70,70,70)

它适用于我,但是当我使用png图像时一切正常并且更改会保存到图像中,但是当我使用JPG图像时,更改不会保存到图像中。 代码中是否缺少某些内容,是否需要保存更改?我该怎么办?

2 个答案:

答案 0 :(得分:0)

尝试:

im.putpixel((50,50), (70, 70, 70))

或者您也可以这样做:

import numpy as np
from PIL import Image

# pix has 4 channels for png and 3 for jpg
pix = np.array(im)

pix[50, 50, 0] = 70      # 0 accesses the first channel
pix[50, 50, 1] = 70      # 1 accesses the second channel
pix[50, 50, 2] = 70      # 2 accesses the third channel

Image.fromarray(pix).save('new_img.jpg')

答案 1 :(得分:0)

使用以前的文件名保存图像。对我来说效果很好

im=Image.open("image.jpg")
pix=im.load()
pix[50,50]=(70,70,70)
img.save("image.jpg")