gpt4 book ai didi

python - 更改 PIL 中的像素颜色值

转载 作者:太空狗 更新时间:2023-10-29 20:44:55 27 4
gpt4 key购买 nike

我需要在 python 中更改图像的像素颜色。除了像素值 (255, 0, 0) 红色外,我需要将每个像素颜色值更改为黑色 (0, 0, 0)。我尝试了以下代码,但没有帮助。

from PIL import Image
im = Image.open('A:\ex1.jpg')
for pixel in im.getdata():
if pixel == (255,0,0):
print "Red coloured pixel"
else:
pixel = [0, 0, 0]

最佳答案

请参阅本维基百科:https://en.wikibooks.org/wiki/Python_Imaging_Library/Editing_Pixels

修改该代码以解决您的问题:

pixels = img.load() # create the pixel map

for i in range(img.size[0]): # for every pixel:
for j in range(img.size[1]):
if pixels[i,j] != (255, 0, 0):
# change to black if not red
pixels[i,j] = (0, 0 ,0)

关于python - 更改 PIL 中的像素颜色值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36468530/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com