Skip to content

Instantly share code, notes, and snippets.

@JasperVanDenBosch
Created November 30, 2023 16:08
Show Gist options
  • Save JasperVanDenBosch/e0ec1b5912459f27cecf56f84393785d to your computer and use it in GitHub Desktop.
Save JasperVanDenBosch/e0ec1b5912459f27cecf56f84393785d to your computer and use it in GitHub Desktop.
Add caption to image
"""Add a text label to an image
Uses Pillow, install with `pip install pillow`
"""
from os.path import expanduser, join, basename
from glob import glob
from PIL import Image, ImageDraw, ImageFont
## full path to your image directory, ~ = your home directory
img_dir = expanduser('~/stimuli/nsd/special100')
## find the paths to each .png file in the directory
img_paths = glob(join(img_dir, '*.png'))[:5]
## define how tall the new area for the label will be
EXTRA_HEIGHT_PIXELS = 50
## Current size of images
WIDTH, HEIGHT = 425, 425
## space between edge and text
MARGIN = 10
## the text to add
LABEL = 'My text label'
## define the font to use
font = ImageFont.truetype('Times New Roman.ttf', 20)
## process each image
for img_fpath in img_paths:
img = Image.open(img_fpath)
## We "crop" with a larger size than the current one to expand the image
## (the numbers are the x and y coordinates of the top-left and bottom-right corners)
img = img.crop((0, 0, WIDTH, HEIGHT+EXTRA_HEIGHT_PIXELS))
## create a "draw" object to add elements
draw = ImageDraw.Draw(img)
## draw a white background for the label
## (the numbers are the x and y coordinates of the top-left and bottom-right corners)
draw.rectangle((0, HEIGHT, WIDTH, HEIGHT+EXTRA_HEIGHT_PIXELS), fill='white')
## Add Text to an image
draw.text((MARGIN, HEIGHT+MARGIN), LABEL, fill='black', font=font)
## Save the edited image
img.save('labeled_'+basename(img_fpath))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment