jump to content

#!/usr/bin/python
"""
A script using Python Imaging Library (PIL) to 
go through all the JPG files in a folder and then
split it into multiple images and save each image

vsbabu AT hotmail DOT com

Scanning photos one by one really annoys me. So, what
I do is I put 4 photos at the same time on my scanner
and get a composite image. Then I run this script on
a folder full of such images to cut individual images
out of such composites.
"""
import Image
import glob
import string

count = 0
# define all your image coordinates. Each image is defined
# as (x1,y1, x2,y2) where x1,y1 is for top-left corner and
# x2,y2 is for bottom right corner
boxes = [
    (17,6,387,277),
    (416,6,781,277),
    (17,303,383,574),
    (416,303,781,574)
]

def split_image(image_file, prefix, boxes, count):
    """splits the image into files named from count"""
    image = Image.open(image_file)
    for i in range(0,len(boxes)):
        op =  prefix + string.zfill(count+i, 4) + '.jpg'
        opi = image.crop(boxes[i])
        opi.save(op,'JPEG')
        print "\t", op
    return count+i+1

for f in glob.glob('*.jpg'):
    print f
    count = split_image(f, 'vsbabu_', boxes,count)