0
votes

I have a series of images that are all the same size and are all of a sign written in black, they're all rather simple (+, -, x, /, 1-9) on a one color background, the background color changes it sometimes is green sometimes blue, sometimes red but always a uniform color.

I am trying to convert those images to a black and white image where the sign is black and the background is always white.

I am doing so to be able to compare the images to find sign duplicates.

So how to do the greyscale conversion using PIL.

And is there a better way to do the comparaison?

thanks

3

3 Answers

1
votes

You may want to look at scipy.ndimageand skimage as those two python libraries will make your life easier dealing with such simple image comparison.
To give you a short view of what you can do with both libraries.

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

But to use the above code you need to make your background black so the label method can work.If you don't want to bother yourself inverting you background to black then you should use the alternative library 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
votes

Here is what I would do :

  • compute the median value of the image colors. If the colors are really uniform, it should be able to segmentate it correctly (be careful no to invert the black/white color when tresholding the image). Otherwise, use a more robust method like a 2-means algorithm on the image's color histogram
  • for sign comparaison, I would go with 2D-crosscorralation (scipy and openCV has a lot of useful methods to do so). Some hints : How can I quantify difference between two images?
1
votes

So, simply convert it to black and white

black_and_white = im.convert('1')

Ah, and you can also use im.getcolors(maxcolors)

http://effbot.org/imagingbook/image.htm - here is documentation

If your picture really has only two colors, use im.getcolors(2) and you will see only two items in this list, and then you will be able to replace them in the image with white and black colours.