简体   繁体   English

在Python上使用PIL更改像素颜色

[英]Changing pixel color using PIL on Python

I'm very new to programming, and I am learning more about image processing using PIL. 我对编程非常陌生,并且正在学习有关使用PIL进行图像处理的更多信息。

I have a certain task that requires me to change every specific pixel's color with another color. 我有一项特定的任务,要求我将每个特定像素的颜色更改为另一种颜色。 Since there are more than few pixels I'm required to change, I've created a for loop to access to every pixel. 由于需要更改的像素不止几个,因此我创建了一个for循环来访问每个像素。 The script "works" at least, however the result is just a black screen with (0, 0, 0) color in each pixel. 脚本至少“有效”,但是结果只是每个像素中具有(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')

The image I have is a grayscale image. 我的图像是灰度图像。 There are specific colors, and there are gradient colors near the borders. 有特定的颜色,并且边框附近有渐变颜色。 I'm trying to replace each specific color with another color, and then replace the gradient colors with another color. 我试图用另一种颜色替换每种特定的颜色,然后用另一种颜色替换渐变颜色。

However for the life of me, I don't understand why my output comes out with a single (0, 0, 0) color at all. 但是,对于我一生来说,我根本不明白为什么我的输出完全只显示一种(0,0,0)颜色。

I tried to look for an answer online and friends, but couldn't come up with a solution. 我试图在网上和朋友那里寻找答案,但无法提出解决方案。

If anyone out there knows what I'm doing wrong, any feedback is highly appreciated. 如果外面有人知道我在做什么错,我们将非常感谢您提供任何反馈意见。 Thanks in advance. 提前致谢。

The issue is that your image is, as you said, greyscale , so on this line: 问题是,正如您所说,您的图像是灰度的 ,因此在此行上:

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

no pixel will ever equal the RGB triplet (255,255,255) because the white pixels will be simply the greyscale vale 255 not an RGB triplet. 没有像素会等于RGB三元组(255,255,255)因为白色像素将只是灰度值255而不是RGB三元组。

It works fine if you change your loop to: 如果将循环更改为:

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

Here is the contrast-stretched result: 这是对比结果:

在此处输入图片说明


You may like to consider doing the conversion using a "Look Up Table" , or LUT, as large numbers of if statements can get unwieldy. 您可能要考虑使用“ Look Up Table”或LUT进行转换,因为大量的if语句可能会变得笨拙。 Basically, each pixel in the image is replaced with a new one found by looking up its current index in the table. 基本上,图像中的每个像素都会替换为一个新像素,该像素可以通过在表中查找其当前索引来找到。 I am doing it with numpy for fun too: 我也用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')

Result - after stretching contrast: 结果-拉伸对比度后:

在此处输入图片说明


I am maybe being a bit verbose above, so if you like more terse code: 上面我可能有点冗长,所以如果您喜欢更简洁的代码:

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')

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

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