在Python上使用PIL更改像素颜色 [英] Changing pixel color using PIL on Python

查看:4676
本文介绍了在Python上使用PIL更改像素颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程新手,我正在学习更多关于使用PIL进行图像处理的知识。

I'm very new to programming, and I am learning more about image processing using PIL.

我有一项任务需要我用另一种颜色更改每个特定像素的颜色。由于我需要更改几个像素,我已经创建了一个for循环来访问每个像素。该脚本至少有效,但结果只是每个像素中带有(0,0,0)颜色的黑色屏幕。

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. The script "works" at least, however the result is just a black screen with (0, 0, 0) color in each pixel.

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.

然而,就我而言,我不明白为什么我的输出会出现单一(0,0,0)颜色。

However for the life of me, I don't understand why my output comes out with a single (0, 0, 0) color at all.

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

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

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

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.

如果你更改你的工作正常循环到:

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:

您可能会喜欢ider使用查找表或LUT进行转换,因为大量的 if 语句可能变得难以处理。基本上,图像中的每个像素都被替换为通过在表中查找其当前索引而找到的新像素。我也用 numpy 来做这件事:

You may like to consider doing the conversion using a "Look Up Table", or LUT, as large numbers of if statements can get unwieldy. 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:

#!/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')

这篇关于在Python上使用PIL更改像素颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆