2012-11-11 215 views
0

我有一系列圖像都是相同的大小,都是黑色的標誌,它們都很簡單(+, - ,x,/, 1-9)在一種顏色的背景上,背景顏色會改變,有時候有時是綠色的,有時是藍色的,有時是紅色的,但始終是統一的顏色。Python圖像庫黑白兩色圖像

我試圖將這些圖像轉換爲黑色和白色圖像,其中標誌是黑色,背景總是白色。

我這樣做是爲了能夠比較圖像來找到重複標誌。

那麼如何使用PIL進行灰度轉換。

還有更好的方法來做比較嗎?

感謝

回答

1

你可能想看看scipy.ndimageskimage那些兩個Python庫將讓您的生活更輕鬆應付這種簡單的圖像比較。
簡要介紹兩種庫的功能。

>>> from scipy.ndimage import find_objects,label 
>>> import scipy.misc   
>>> img=scipy.misc.imread('filename.jpg') 
>>> labeled,number=label(img) # (label) returns the lebeled objects while 
           # (number) returns the numer ofthe labeled signs 
>>> signs=find_objects(labeled) #this will extract the signs in your image 
#once you got that,you can simply determine 
# if two images have the same sign using sum simple math-work. 

但使用你需要讓你的背景上的黑色上述代碼,以便在標籤方法可以工作。如果你不想打擾自己翻轉你的背景爲黑色,那麼你應該使用備用庫skimage

>>> import skimage.morphology.label 
>>> labeled=skimage.morphology.label(img,8,255) #255 for the white background 
               #in the gray-scale mode 
#after you label the signs you can use the wonderful method 
#`skimag.measure.regionprops` as this method will surely 
# help you decide which two signs are the same. 
1

所以,簡單地將其轉換爲黑白

black_and_white = im.convert('1') 

啊,你也可以使用im.getcolors(maxcolors)

http://effbot.org/imagingbook/image.htm - 這裏是文檔

如果您的圖片真的只有兩種顏色,使用im.getcolors(2),你會在此列表中看到只有兩個項目,然後你無線將能夠用白色和黑色替換圖像。

1

這裏是我會做什麼:

  • 計算圖像色彩的中間值。如果顏色真的是一致的,它應該能夠正確分割它(當對圖像進行閾值處理時,請注意不要反轉黑白色)。否則,在圖像的顏色直方圖上使用更穩健的方法,如圖像的顏色直方圖
  • 用於符號比較,我將使用2D交叉相關(scipy和openCV有很多有用的方法來實現這一點)。一些提示:How can I quantify difference between two images?