簡體   English   中英

Python圖像庫將兩種顏色的圖像轉換為黑白

[英]Python Image Library two color image to black and white

我有一系列的圖像,它們的大小都是一樣的,並且都是用黑色寫的,它們在一種顏色的背景上都很簡單(+,-,x,/,1-9),背景色更改有時是綠色,有時是藍色,有時是紅色,但始終是統一的顏色。

我正在嘗試將這些圖像轉換為符號為黑色且背景始終為白色的黑白圖像。

我這樣做是為了能夠比較圖像以查找符號重復項。

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

有沒有更好的方法進行比較?

謝謝

因此,只需將其轉換為黑白

black_and_white = im.convert('1')

嗯,您也可以使用im.getcolors(maxcolors)

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

如果您的圖片實際上只有兩種顏色,請使用im.getcolors(2) ,您將在此列表中僅看到兩項,然后可以在圖像中用白色和黑色替換它們。

這是我會做的:

  • 計算圖像顏色的中間值。 如果顏色確實是均勻的,則應該能夠正確地對其進行分割(在對圖像進行貼圖處理時,請注意不要將黑色/白色反轉)。 否則,對圖像的顏色直方圖使用更強大的方法(例如2均值算法)
  • 為了進行符號比較,我將使用2D互相關(scipy和openCV有很多有用的方法可以做到這一點)。 一些提示: 如何量化兩個圖像之間的差異?

您可能需要查看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.  

但是要使用上面的代碼,您需要將背景設置為黑色以使label方法可以工作。如果您不想自己將背景轉換為黑色,則應該使用替代庫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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM