【问题标题】:Changing pixel color value in PIL在 PIL 中更改像素颜色值
【发布时间】:2016-07-27 21:11:51
【问题描述】:

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

【问题讨论】:

  • 注意字符串文字中的反斜杠。使用原始字符串 r'A:\ex1.jpg' 或转义它们:'A:\\ex1.jpg'。或者只是在路径名中使用斜杠:'A:/ex1.jpg'

标签: python python-imaging-library


【解决方案1】:

请参阅此维基书: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)

【讨论】:

  • OP 不是需要反过来吗? (将非红色像素改为黑色)?
  • 不应该是 for i in range(pixels.size[0]): ?
  • 文档描述 load() 很慢:Accessing individual pixels is fairly slow. If you are looping over all of the pixels in an image, there is likely a faster way using other parts of the Pillow API. 他们没有指定除此之外的任何内容,但 loxaxs' answer 是一个合理的猜测。
【解决方案2】:

你可以使用img.putpixel:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

      享受吧!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-31
        • 1970-01-01
        • 2017-09-26
        • 1970-01-01
        • 1970-01-01
        • 2019-01-24
        相关资源
        最近更新 更多