Python Image Library将两种颜色的图像改为黑白图像

时间:2012-11-11 19:38:57

标签: python python-imaging-library

我有一系列相同尺寸的图像,都是用黑色写的标志,它们在单色背景上都很简单(+, - ,x,/,1-9),背景颜色有时变绿有时是蓝色,有时是红色但总是颜色均匀。

我正在尝试将这些图像转换为黑白图像,其中标志为黑色,背景始终为白色。

我这样做是为了能够比较图像以找到符号重复。

那么如何使用PIL进行灰度转换。

还有更好的方法来进行比较吗?

感谢

3 个答案:

答案 0 :(得分:1)

所以,只需将其转换为黑白

即可
black_and_white = im.convert('1')

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

http://effbot.org/imagingbook/image.htm - 这是文档

如果您的图片真的只有两种颜色,请使用im.getcolors(2),此列表中只会看到两个项目,然后您就可以用白色和黑色替换它们。

答案 1 :(得分:1)

以下是我要做的事情:

  • 计算图像颜色的中值。如果颜色非常均匀,则应该能够正确分割(在对图像进行阈值处理时,请注意不要反转黑/白色)。否则,在图像的颜色直方图上使用更稳健的方法,如双均值算法
  • 对于符号比较,我会选择2D-crosscorralation(scipy和openCV有很多有用的方法)。一些提示:How can I quantify difference between two images?

答案 2 :(得分: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 < / p>

>>> 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.