Reputation: 6895
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
Upvotes: 0
Views: 3025
Reputation: 877
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.
Upvotes: 1
Reputation: 485
You may want to look at scipy.ndimage
and 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.
Upvotes: 1
Reputation: 11002
Here is what I would do :
Upvotes: 1