Created
August 30, 2018 15:14
-
-
Save philmikejones/c2465a992b678e7fde464caed60dd569 to your computer and use it in GitHub Desktop.
Layout multiple images onto one canvas with Python pillow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Pastes Lexis surface diagrams and HAPC plots together | |
import os | |
import glob | |
from subprocess import call | |
from PIL import Image, ImageDraw, ImageFont | |
# Get country code list | |
countries = glob.glob("mort_*.png") | |
countries = sorted(countries) | |
## http://stackoverflow.com/questions/3136689/find-and-replace-string-values-in-python-list | |
## Get the country codes | |
countries = [countries.replace("mort_", "") for countries in countries] | |
countries = [countries.replace(".png", "") for countries in countries] | |
# Set output canvas size | |
dpi = 300 | |
width = int((42.0 / 2.54) * dpi) | |
height = int((29.7 / 2.54) * dpi) | |
for i in countries: | |
# Create blank canvas | |
canvas = Image.new("RGBA", (width, height), color = (255, 255, 255)) | |
# Open Lexis surface plot, trim whitespace, paste into canvas | |
lexis = Image.open("mort_" + i + ".png") | |
canvas.paste(lexis) | |
# Lexis plots place females on left; males on right | |
# Copy this layout for HAPC plots | |
# Paste in HAPC female plot | |
pastex = 0 | |
pastey = int(height / 2) | |
hapc_female = Image.open("cohort_" + i + "_female.png") | |
canvas.paste(hapc_female, box = (pastex, pastey)) | |
# Paste in HAPC male plot | |
pastex = int(width / 2) | |
hapc_male = Image.open("cohort_" + i + "_male.png") | |
canvas.paste(hapc_male, box = (pastex, pastey)) | |
# Add annotations | |
draw = ImageDraw.Draw(canvas) | |
font = ImageFont.truetype("FreeMono.ttf", 100) | |
draw.text((20, 20), "Country: " + i, | |
fill = (0, 0, 0, 255), font = font) | |
# Save | |
filename = "country_" + i + ".png" | |
canvas.save(filename) |
You just need four images, each about 210x148.5mm (A5) landscape. Although you can of course modify the script to use any number/size images you like
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is great! Where do you provide the data so that I can try out your code?