打印图像中<10,10,10的像素

2024-04-25 06:55:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,希望有人指点我的下一个方向。我用的是PIL。做了相当多的研究,但我还是被卡住了!在

我需要得到每个像素的rgb,从0,0开始,沿着y坐标一直沿着每一行。它是一个bmp,只有黑白两种颜色,但我只希望python打印介于10,10,10和0,0,0之间的像素。有人能给我一些智慧吗?在


Tags: pil颜色rgb像素方向新手bmp指点
1条回答
网友
1楼 · 发布于 2024-04-25 06:55:12

如果您确定r==g==b适用于所有像素,则此方法应该有效:

from PIL import Image

im = Image.open("g.bmp")       # The input image. Should be greyscale
out = open("out.txt", "wb")    # The output.

data = im.getdata()            # This will create a generator that yields
                               # the value of the rbg values consecutively. If
                               # g.bmp is a 2x2 image of four rgb(12, 12, 12) pixels, 
                               # list(data) should be 
                               # [(12,12,12), (12,12,12), (12,12,12), (12,12,12)]

for i in data:                   # Here we iterate through the pixels.
    if i[0] < 10:                # If r==b==g, we only really 
                                 # need one pixel (i[0] or "r")

        out.write(str(i[0])+" ") # if the pixel is valid, we'll write the value. So for
                                 # rgb(4, 4, 4), we'll output the string "4"
    else:
        out.write("X ")          # Otherwise, it does not meet the requirements, so
                                 # we'll output "X"

如果由于某种原因不能保证r==g==b,请根据需要调整条件。例如,如果您希望平均值为10,可以将条件更改为类似

^{pr2}$

还要注意,对于灰度格式的文件(与彩色文件格式中的灰度图像相反)im.getdata()将简单地将灰度级别作为单个值返回。所以对于rgb(15, 15, 15)的2x2图像,list(data)将输出[4, 4, 4, 4],而不是{}。在这种情况下,{cd9>而不是

相关问题 更多 >