I'm using Pillow with Python 3.3, and for each image I have, I want to analyse all pixels colors and calculate if each color is nearest to white or to black. I've tried with Euclidean distance with this formula:
>>>a,b=(127,255) #color value of pixel at position (1,1)
>>>whitedist=sqrt((a-255)**2 + (b-255)**2)
>>>print (whitedist)
128.0
Pixels have two values because I'm working with a greyscale image. The thing is that of course I can't do this for each pixel of a 128x128 image, so I tried to write my first "for" cycle ever:
colors=im.getdata() #all pixel values
for item in col:
for item in range (0, 127):
print ("B") #if the value is between 0 and 127 the color is nearer to black
this was a totally stupid attempt, python went into an infinite loop and I had to quit it. My problem is that I have a raw idea of what to do but I don't know python so well to translate my reasoning into code. I think my reasoning it's not completely wrong but I can't find a way to translate it into code.
Since list(im.getdata()) returns a list of tuples, one tuple for each pixel containing two values, what I think I should do is to apply the formula whitedist=sqrt((a-255)**2 + (b-255)**2)
to each tuple and if the result of the formula is <128, tag the pixel as "dark", if >128 then tag the pixel as "light", then I need to count all dark and light pixels and see if the image has more dark or light pixels.
Is it totally wrong to do this with a for cycle?