Learning Python and the Python Imaging Library

So, I'm learning python at the moment and I think that it's a really great language. When I'm learning a new language, I usually look on the interwebs for funny programming exercises, like ProjectEuler.net and I also did this time. But I also had a problem of my own I needed to solve.

I had around 260 pictures that looked like this:
Image 1 Image 2

The images I want has a black 1 pixel thick border around them, so to get that image, I need to find the border. Python Image Library to the rescue! This is a wonderful module and it's really easy to work with. Below is the code I ended up with for finding the black border in the image and saving the image encased in the border:

import Image,sys

filename=sys.argv[1]

im = Image.open(filename)
p=im.load()

# calculate middle of pictures x and y axis
s=im.size
hx=(int)(s[0]/2)
hy=(int)(s[1]/2)

# find left border
x=0
while(p[x,hy] != (0,0,0)):
    x=x+1
left=x+1

# find rigth border
x=im.size[0]-1
while(p[x,hy] != (0,0,0)):
    x=x-1
right=x
#find top border
y=0
while(p[hx,y] != (0,0,0)):
    y=y+1
top=y+1
# find bottom border
y=im.size[1]-1
while(p[hx,y] != (0,0,0)):
    y=y-1
bottom=y

# crop the original image to include only the part I want
# and save it to the original file
new = im.crop( (left, top, right, bottom) )
new.save(filename)

Of course, I could implement "error-handling" like if no filename is given, but it's not necessary since I use the tool like this:

for i in $(ls *.png); do python egdefinder.py $i; done

If you want to use it, be my guest. If you have any comments on my coding, please feel free to tell me. :-)


Written by Jannich Brendle man 25 oktober 2010 In Programming

tags: easyimage processingpython

Related posts

social