Wednesday, 08 January 2014 14:09

Combine several images into one with Python and PIL

Written by 
Rate this item
(0 votes)

I have a sub directory data with multiple jpg picture files. The files are named in a way that they are sorted automatically by the os. In my case this is YYYYMM-xy.jpg where YYYY is the year and MM is the month. This is because for this project I made one picture every month over one year. The sub string -xy is extracted by the Python program and is rendered as text onto each image.

 

files with numbers

 With the following Python script I can combine these eight images into one.

import os
import Image
import ImageFont
import ImageDraw


img_list = []
img_text = []
img_path = "./data/"
width = 176 #684
height = 187 #1024
text_pos_x = 3 #10
text_pos_y = 3 #10
text_size = 10 #50
rows = 2
columns = 0


for file in os.listdir( img_path ):
# Search images
if file.endswith(".jpg"):
# open images
img_list.append( Image.open( img_path + file ) )
# Extract text to render on the image from the file name
img_text.append( file.split("-")[1].split(".")[0] )
# Print info
print 'File:', file, ' => ', img_text[-1]


for image in img_list:
# resize images
image.thumbnail( (width, height) )

columns = len(img_list)/rows

#creates a new empty image, RGB mode
mosaic = Image.new( 'RGB', ( columns * width, rows * height ) )

# Prepare draw and font objects to render text
draw = ImageDraw.Draw(mosaic)
font = ImageFont.truetype("C:/Windows/Fonts/arial.ttf",text_size)

k=0
for j in xrange( 0, rows * height, height ):
for i in xrange( 0, columns * width, width ):
# paste the image at location i,j:
mosaic.paste( img_list[k], (i,j) )
# render text at location i,j:
draw.text((i + text_pos_x, j + text_pos_y), img_text[k], font=font)
# Select next image and text
k = k + 1

# Save image to file
mosaic.save('mosaic.jpg')

 

The Result is written to the file mosaic.jpg. 

mosaic

Read 1636 times Last modified on Friday, 26 June 2015 11:40

Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.