Python Image manipulation

Python can be used to manipulate or create pictures. One way is to use PIL , the Python Image Library. This page contains some simple examples to get started.

For the examples below this image will be used for testing the apps. Download the image and save it as “Linux_Logo.png” in the same directory as the python scripts ( or change the filename in the script).

Example 1: Read values .png file per pixel
This program determines the size of the picture, and then reads and prints the values of each pixel:


from PIL import Image
png_file_name='Linux_Logo.png'
# change to the filename. use full path if the png-file is not in the same dir.

def MAIN():
im = Image.open(png_file_name)
pix = im.load()
image_size= im.size
print 'image size is ' , image_size
xrange = image_size[0] # set the x-range of the image from the image size.
yrange = image_size[1]

for j in range (0,xrange):
for i in range(0,yrange):
value = pix[j,i]
print value

MAIN()

Example 2: Read values and change first component (red in RGB) to 255
This program results in the logo to be transformed to a more ‘red-coloured’ picture.
It reads all pixels, changes the value of the first byte in RGB ( RED) to 255, and keeps the other colours.
The result should be something like this:


from PIL import Image
png_file_name='Linux_Logo.png'
# change the filename to the picture you want to use.

newData = list()

def MAIN():
img = Image.open(png_file_name)
pix = img.load()
image_size= img.size
print 'image size is ' , image_size
yrange = image_size[0]
xrange = image_size[1]

for j in range (0,xrange):
for i in range(0,yrange):
value = pix[i,j]
new_value= (255,value[1] , value[2],value[3])
#Example:
#Make first (Red in RGB) byte 255 ( maxvalue)
#keep other components what they were.
newData.append(new_value)

img.putdata(newData)
img.save( "result.png")

MAIN()

This entry was posted in Linux, Python. Bookmark the permalink.