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

时间:2012-10-24 13:25:48

标签: python python-imaging-library

我是python的新手,希望指向下一个方向。我正在使用PIL。做了一些研究,我仍然坚持!

我需要从0,0开始每个像素的rgb并沿着y坐标一直沿着每一行。它只是bmp而且只有黑白,但我只想让python打印10,10,10和0,0,0之间的像素。有人能给我一些智慧吗?

1 个答案:

答案 0 :(得分:0)

如果您确定所有像素都为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,则可以将条件更改为

if sum(i) <= 30: # Equivalent to sum(i)/float(len(i)) <= 10 if we know the length is 3

另请注意,对于灰度格式文件(与彩色文件格式的灰度图像相对),im.getdata()将简单地将灰度级返回为单个值。因此,对于rgb(15, 15, 15)的2x2图像,list(data)将输出[4, 4, 4, 4]而不是[(4, 4, 4), (4, 4, 4), (4, 4, 4), (4, 4, 4)]。在这种情况下,在分析时,请仅参考i而不是i[0]