This is a script I wrote to to divide pictures into two colors .I did this because all the seemingly black and white mazes weren't read as just two colors but a bunch of them.So I thought why not write a script to bipolarize the image myself.
The script is as follows:
import sys
import Image
file=Image.open(sys.argv[1])
file=file.convert('RGB')
w,h=file.size
color={}
for i in range(w):
for j in range(h):
aux=file.getpixel((i,j))
if aux >(200,200,200):
file.putpixel((i,j),(255,0,0))
else:
file.putpixel((i,j),(0,0,0))
file.save(sys.argv[1])
The problem when the following script tries to read the colors present in the result of the above script
import sys
import Image
file=Image.open(sys.argv[1])
file=file.convert('RGB')
w,h=file.size
color={}
for i in range(w):
for j in range(h):
aux=file.getpixel((i,j))
if aux not in color:
color[aux]=1
else:
color[aux]+=1
print "file stat"
print color
The picture doesn't appear to polarized into just two colors, even if it does so visually
What is going on?
I think that the problem here is that the source file you are using is compressed (probably a .jpeg file). When you pass
sys.argv[1]
tofile.save
PIL decides whether to compress the "polarized" image based on the file extension. So ifsys.argv[1]=="test.jpg"
then the file written to disk will be compressed.Compression can induce colours in between the pure red and black that you are expecting.
An easy way around this problem is to write the output to file using an uncompressed format such as .png instead.
Incidentally, this "polarization" is usually referred to as "thresholding" and the two-tone image you are generating is a thresholded image.
Also, I don't think it's a great idea to use the word
file
as a variable name, since it is used for other things, e.g. http://docs.python.org/2/library/functions.html#fileThe version of your code below demonstrates the difference between letting PIL write a compressed version of your thresholded image, compared to an uncompressed version: