Python 更改 PIL 中的像素颜色值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36468530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:56:01  来源:igfitidea点击:

Changing pixel color value in PIL

pythonpython-imaging-library

提问by Kuppo

I need to change pixel color of an image in python. Except for the pixel value (255, 0, 0) red I need to change every pixel color value into black (0, 0, 0). I tried the following code but it doesn't helped.

我需要在 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]

回答by magni-

See this wikibook: https://en.wikibooks.org/wiki/Python_Imaging_Library/Editing_Pixels

请参阅此维基书:https: //en.wikibooks.org/wiki/Python_Imaging_Library/Editing_Pixels

Modifying that code to fit your problem:

修改该代码以适应您的问题:

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)

回答by innuendo

Taking the question to an extreme level, here's how to randomly change the channels in PIL (neglecting any 0, which I consider as background)

将问题带到一个极端的水平,这里是如何随机更改 PIL 中的通道(忽略任何 0,我认为是背景)

rr, gg, bb = in_img.split()
rr = rr.point(lambda p: 0 if p==0 else np.random.randint(256) )
gg = gg.point(lambda p: 0 if p==0 else np.random.randint(256) )
bb = bb.point(lambda p: 0 if p==0 else np.random.randint(256) )
out_img = Image.merge("RGB", (rr, gg, bb))
out_img.getextrema()
out_img.show()

Enjoy!

享受!

回答by Anno

You could use img.putpixel:

你可以使用img.putpixel

im.putpixel((x, y), (255, 0, 0))

回答by loxaxs

Here is the way I'd use PIL to do what you want:

这是我使用 PIL 做你想做的事情的方式:

from PIL import Image

imagePath = 'A:\ex1.jpg'
newImagePath = 'A:\ex2.jpg'
im = Image.open(imagePath)

def redOrBlack (im):
    newimdata = []
    redcolor = (255,0,0)
    blackcolor = (0,0,0)
    for color in im.getdata():
        if color == redcolor:
            newimdata.append( redcolor )
        else:
            newimdata.append( blackcolor )
    newim = Image.new(im.mode,im.size)
    newim.putdata(newimdata)
    return newim

redOrBlack(im).save(newImagePath)