4
EXTRACTING PIXEL VALUES OF AN IMAGE IN PYTHON
Python
Pixel
Image

I wanted to extract each pixel values so that i can use them for locating simple objects in an image. Every image is made up of pixels and when these values are extracted using python, four values are obtained for each pixel (R,G,B,A). This is called the RGBA color space having the Red, Green, Blue colors and Alpha value respectively.

In python we use a library called PIL (python imaging Library). The modules in this library is used for image processing and has support for many file formats like png, jpg, bmp, gif etc. It comes with large number of functions that can be used to open, extract data, change properties, create new images and much more…

PIL comes pre installed with python2.7 in Ubuntu but for windows it has to be installed manually. But for either operating systems having python2.7 or more can be downloaded from here. and for python3 it can be downloaded from here.

each pixel value can be extracted and stored in a list.Though IDLE shell can be used for it, it can take a long time to extract the values and hence its recommended that it is done using command line interface. The procedure for extraction is :

  1. import the Image module of PIL into the shell:

    >>>from PIL import Image

  2. create an image object and open the image for reading mode:

    >>>im = Image.open(‘myfile.png’, ‘ r’)


    myfile is the name of the image to be read and give the appropriate file format. that is if its a jpeg image then give it as myfile.jpg
  3. we use a function of Image module called getdata() to extract the pixel values. this scans the image horizontally from left to right starting at the top-left corner. The values got from each pixel is then added into a list. Finally what we get is a list with each pixel value as a set of 4 values(R,G,B.A).

    >>>pix_val = list(im.getdata())

    pix_val is the list that contains all the pixel values which can be printed to see those values But the list got is a list of sets and some times its needed to flatten the list for example if the list is like: [(123,124,145,120), (345,453,234,124),……] and the list that is needed is [123, 124, 145, 120, 345, 453, 234, 124….] then the command to flatten the list is:

    >>> pix_val_flat = [x for sets in pix_val for x in sets]

    This list comprehension extracts each element of each set in the list pix_val and all the elements are stored in pix_val_flat. Thus this can be compiled into a script or made into a function which can be used in any image processing projects later. PIL is one of the many methods for image processing. pygames or numpy can be used with their respective modules to process images as well.
Author

Notifications

?