我是python的新手,希望大家能给我指出下一个方向。我正在使用PIL。做了相当多的研究,我还是被卡住了!
我需要得到每个像素的rgb,从0,0开始,沿着每一行一直到y坐标。这是一个bmp,只有黑白,但我只想让python打印10,10,10和0,0,0之间的像素。有人能给我一些建议吗?
发布于 2012-10-24 22:29:56
如果你确定所有像素都是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]
https://stackoverflow.com/questions/13050225
复制相似问题