Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop all image pixels and tell whether they are black or white

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__
like image 772
Richard Knop Avatar asked Oct 19 '10 18:10

Richard Knop


People also ask

How can you tell if a picture is pure black?

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.

Why do we use nested for loops to process an image?

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.


2 Answers

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 .

like image 146
Brian Avatar answered Nov 09 '22 14:11

Brian


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?

like image 32
Paulo Scardine Avatar answered Nov 09 '22 13:11

Paulo Scardine