Python 打印图像中的像素<;10,10,10
我是python新手,希望能为我指出下一个方向。我正在使用PIL。我做了一点调查,但我还是被卡住了Python 打印图像中的像素<;10,10,10,python,python-imaging-library,Python,Python Imaging Library,我是python新手,希望能为我指出下一个方向。我正在使用PIL。我做了一点调查,但我还是被卡住了 我需要得到每个像素的rgb,从0,0开始,沿着y坐标下的每一行。它是一个bmp,只有黑白,但我只希望python打印10,10,10和0,0,0之间的像素。有人能给我一些建议吗?如果你确定所有像素都是r==g==b,那么这应该是可行的: from PIL import Image im = Image.open("g.bmp") # The input image. Should b
我需要得到每个像素的rgb,从0,0开始,沿着y坐标下的每一行。它是一个bmp,只有黑白,但我只希望python打印10,10,10和0,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"
还请注意,对于灰度格式文件(与彩色文件格式的灰度图像相反)
im.getdata()
将仅返回灰度值作为单个值。因此,对于rgb(15,15,15)
的2x2图像,列表(数据)
将输出[4,4,4,4]
,而不是[(4,4,4),(4,4,4),(4,4,4),(4,4,4)]
。在这种情况下,分析时,只参考i
而不是i[0]
是否要打印像素值?您尝试过什么?要获取rgb值,请将图像转换为“rgb”,然后使用getpixel
。要查看(x,y,z)<(10,10,10)
doall(x<10代表rgb.getpixel(i,j))
[这假设(a,b,c)
iffa,否则使用元组比较。]@Bakuriu:我的大脑必须暂时检查以建议使用sum(),但肯定getpixel()
需要一个元组参数。@eryksun哦,我忘了。无论如何,从rgb.getpixel(i,j)
更改为正确的rgb.getpixel((i,j))
并不难。无论如何,对于每个像素(如答案所示),使用getdata
进行迭代应该比调用getpixel
快得多。
if sum(i) <= 30: # Equivalent to sum(i)/float(len(i)) <= 10 if we know the length is 3