【问题标题】:Changing pixel color using PIL on Python在 Python 上使用 PIL 更改像素颜色
【发布时间】:2018-05-29 09:24:16
【问题描述】:

我对编程很陌生,我正在学习更多关于使用 PIL 进行图像处理的知识。

我有一项任务需要我将每个特定像素的颜色更改为另一种颜色。由于需要更改的像素不止几个,因此我创建了一个 for 循环来访问每个像素。脚本至少“有效”,但结果只是一个黑屏,每个像素都有 (0, 0, 0) 颜色。

from PIL import Image
img = Image.open('/home/usr/convertimage.png')
pixels = img.load()
for i in range(img.size[0]):
    for j in range(img.size[1]):
            if pixels[i,j] == (225, 225, 225):
                pixels[i,j] = (1)
            elif pixels[i,j] == (76, 76, 76):
                pixels [i,j] = (2)
            else: pixels[i,j] = (0)
img.save('example.png')

我拥有的图像是灰度图像。有特定的颜色,边框附近有渐变色。我试图用另一种颜色替换每种特定颜色,然后用另一种颜色替换渐变颜色。

但是对于我这辈子来说,我完全不明白为什么我的输出是单一的 (0, 0, 0) 颜色。

我试图在网上和朋友中寻找答案,但无法提出解决方案。

如果有人知道我做错了什么,我们非常感谢任何反馈。提前致谢。

【问题讨论】:

  • 这里似乎有些混乱 - 你说你的图像是灰度的,但有特定的颜色和渐变。它不能同时是彩色和灰度的。也许分享你的图片?
  • imgur.com/OpL3xmK 这是我拥有的原始图像。有 3 种基本颜色(或应该是),它们是黄色、红色和白色。 imgur.com/WlD1yDg 这是我将灰度转换为的图像的结果。每个类都有诸如 (225, 225, 225) 之类的音调。 imgur.com/XEWw7HM 这是我想将图像转换成的类型。在这种情况下,每个特定类别都必须具有不同的颜色,例如颜色为 (2, 2 ,2) 的汽车。
  • 我的回答解决了您的问题吗?如果是这样,请考虑接受它作为您的答案 - 通过单击计票旁边的空心对勾/复选标记。如果没有,请说出什么不起作用,以便我或其他人可以进一步为您提供帮助。谢谢。 meta.stackexchange.com/questions/5234/…

标签: python image loops python-imaging-library


【解决方案1】:

问题是,正如你所说,你的图像是灰度,所以在这一行:

if pixels[i,j] == (225, 225, 225):

没有像素会等于 RGB 三元组(255,255,255),因为白色像素只是灰度值255 而不是 RGB 三元组。

如果您将循环更改为:

        if pixels[i,j] == 29:
            pixels[i,j] = 1
        elif pixels[i,j] == 179:
            pixels [i,j] = 2
        else:
            pixels[i,j] = 0

这是对比拉伸的结果:


您可能希望考虑使用 “查找表” 或 LUT 进行转换,因为大量的 if 语句可能会变得笨拙。基本上,图像中的每个像素都被替换为通过在表中查找其当前索引找到的新像素。我和numpy 一起做这件事也是为了好玩:

#!/usr/local/bin/python3
import numpy as np
from PIL import Image

# Open the input image
PILimage=Image.open("classified.png")

# Use numpy to convert the PIL image into a numpy array
npImage=np.array(PILimage)

# Make a LUT (Look-Up Table) to translate image values. Default output value is zero.
LUT=np.zeros(256,dtype=np.uint8)
LUT[29]=1    # all pixels with value 29, will become 1
LUT[179]=2   # all pixels with value 179, will become 2

# Transform pixels according to LUT - this line does all the work
pixels=LUT[npImage];

# Save resulting image
result=Image.fromarray(pixels)
result.save('result.png')

结果 - 拉伸对比度后:


我上面可能有点冗长,所以如果你喜欢更简洁的代码:

import numpy as np
from PIL import Image

# Open the input image as numpy array
npImage=np.array(Image.open("classified.png"))

# Make a LUT (Look-Up Table) to translate image values
LUT=np.zeros(256,dtype=np.uint8)
LUT[29]=1    # all pixels with value 29, will become 1
LUT[179]=2   # all pixels with value 179, will become 2

# Apply LUT and save resulting image
Image.fromarray(LUT[npImage]).save('result.png')

【讨论】:

  • 我明白我做错了什么。感谢您显示我的错误!非常感谢。
猜你喜欢
  • 2016-07-27
  • 1970-01-01
  • 1970-01-01
  • 2011-11-08
  • 1970-01-01
  • 2019-01-24
  • 1970-01-01
  • 1970-01-01
  • 2015-07-31
相关资源
最近更新 更多