I have a simple black and white only gif image (400x400px let's say).
I need to get all pixels from that image and find whether they are black or white. I need to create a dictionary with the information about the pixels and their colors then.
I'm pretty new to python so I am kinda struggling with this. But here goes my script so far:
#!/usr/bin/env python
import os
import Image
os.chdir("D:/python-projects")
aImage = Image.open("input.gif")
aPixelsBlackOrWhiteDictionary = {}
# now I need to fill the dictionary with values such as
# "X,Y": 0
# "X,Y": 1
# where X,Y are coordinates and 0/1 i the pixel color (b/w)
Basically I want the final dictionary to be something like this:
"0,0" : 0 # pixel with X=0,Y=0 coordinates is black
"1,0" : 1 # pixel with X=1,Y=0 coordinates is White
EDIT:
When I try:
print aImage[0, 0]
I get an error:
Traceback (most recent call last):
File "D:\python-projects\backprop.py", line 15, in <module>
print aImage[0, 0]
File "C:\Python26\lib\site-packages\pil-1.1.7-py2.6-win32.egg\Image.py", line
512, in __getattr__
raise AttributeError(name)
AttributeError: __getitem__
By checking for len(clrs) == 1 you can verify if the image contains only one color and by looking at the second element of the first tuple in clrs you can infer the color.
Nested Loops and Image Processing. Use nested loops to demonstrate how to do simple image processing, by iterating through each pixel in an image and making some changes.
You should be using getpixel
rather than using indexing operators. Note that this may be very slow. You would be better off using getdata
, which returns all of pixels as a sequence.
See http://effbot.org/imagingbook/image.htm .
Try:
pix = aImage.load()
print pix[x, y]
Also note that you can use tuples as dictionary keys, you can use mydict[(x, y)] instead of mydict["x,y"].
This pixel information is already stored in the image, why store it in a dict?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With