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
适用于所有像素,则此方法应该有效:如果由于某种原因不能保证
^{pr2}$r==g==b
,请根据需要调整条件。例如,如果您希望平均值为10,可以将条件更改为类似还要注意,对于灰度格式的文件(与彩色文件格式中的灰度图像相反)}。在这种情况下,{cd9>而不是
im.getdata()
将简单地将灰度级别作为单个值返回。所以对于rgb(15, 15, 15)
的2x2图像,list(data)
将输出[4, 4, 4, 4]
,而不是{相关问题 更多 >
编程相关推荐