2012-10-24 112 views
0

我是python的新手,希望能夠指向下一個方向。我正在使用PIL。做了一些公正的研究,但我仍然堅持下去!在圖像中打印像素<10,10,10

我需要得到從0,0開始的每個像素的rgb,並沿着y座標一直沿着每一行。它是一個bmp,只有黑色和白色,但我只希望python打印介於10,10,10和0,0,0之間的像素。有人能給我一些智慧嗎?

+2

是否要打印像素值?你有什麼嘗試? – Matt

+1

獲取rgb值將圖像轉換爲「RGB」並使用「getpixel」。 (x,y,z)<(10,10,10)'做'all(x <10 for x in rgb.getpixel(i,j))'[this假定'(a,b, c)<(A,B,C)'iff'a Bakuriu

+0

@Bakuriu:我的大腦必須暫時檢出才能使用sum()但肯定'getpixel()'需要一個元組參數。 – eryksun

回答

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]