更改PIL中的像素颜色值

时间:2016-04-07 06:42:13

标签: python python-imaging-library

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

4 个答案:

答案 0 :(得分:9)

请参阅此wikibook: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):
            pixels[i,j] = (0, 0 ,0)

答案 1 :(得分:1)

以下是我使用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)

答案 2 :(得分:1)

将问题讲到一个极端的水平,这里是如何随机更改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()

享受!

答案 3 :(得分:0)

为什么不使用img.putpixel((i,j),(255, 0, 0))

请参阅:https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.putpixel