简体   繁体   English

更改 PIL 中的像素颜色值

[英]Changing pixel color value in PIL

I need to change pixel color of an image in python.我需要在 python 中更改图像的像素颜色。 Except for the pixel value (255, 0, 0) red I need to change every pixel color value into black (0, 0, 0).除了像素值 (255, 0, 0) 红色我需要将每个像素颜色值更改为黑色 (0, 0, 0)。 I tried the following code but it doesn't helped.我尝试了以下代码,但没有帮助。

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]

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)

你可以使用img.putpixel

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

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!享受!

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM