Category Archives: Python

Handling Images With Python

Here’s a quick reminder of how to handle image files with Python.
First of all, it’s always good to have the numpy module.
Other than that, the already included Image and ImageOps modules are also very handy.

An easy way to convert an image into grayscale and then save it back.

import Image, ImageOps
mona_lisa ="monalisa.jpeg")
mona_lisa = ImageOps.grayscale(resim)"monsa_lisa_BW.jpeg")

Ok that was simple. Here’s how you can manipulate it easily with numpy.

import Image, numpy
mona_lisa ="monalisa.jpeg")
theArray = numpy.asarray(mona_lisa) # Now we have the image as a numpy array
for x in xrange(0,theArray.shape[0]) :
    for y in xrange(0,theArray.shape[1]) : theArray[x][y] = theArray[x][y]-128
theoutput = Image.fromarray(numpy.uint8(theArray))"monalisa8bit.jpeg")

The code above will open the monalisa.jpeg image, and subtract the value 128 from each value. And then convert the new matrix (or numpy array) into an 8bit unsigned integer image, then save it as monalisa8bit.jpeg