Python – numpy – pillow – translate text on canvas

A python program to draw a text on canvas using pillow and translate it using numpy arrays.

A program to translate text on canvas.
Uses numpy arrays for translating and pillow to draw text.
Author: Jithesh Kuyyalil (
Date  : May 29, 2019
from PIL import Image, ImageDraw, ImageFont
import numpy as np

img ="L", (500, 500))
array_raw = np.asarray(img)
font_size = 20
font_path = 'DroidSansMono.ttf'
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(font_path, font_size)
# draw text to extract the image array
draw.text((0, 0), "HELLO", fill='white', font=font)
img_array = np.asarray(img)
# non zero elements in the image array
non_zero = np.nonzero(img_array)
# find the edges of the text row and column wise
row_min, row_max = min(non_zero[0]), max(non_zero[0])
col_min, col_max = min(non_zero[1]), max(non_zero[1])
# extract the text pixels as array
text_pixel = img_array[row_min:row_max+1, col_min:col_max + 1]
# make array_raw writable
# amount of translation
trans_row = 20
trans_col = 400
# check for boundary condtions so that text don't cross canvas edges
# 500x500 is the canvas size
if row_min+trans_row >=0 and row_max+1+trans_row =0 and col_max+1+trans_col <=500:
    # paste the text into the original canvas
    array_raw[row_min+trans_row: row_max+1+trans_row, col_min+trans_col:col_max+1+trans_col] = text_pixel
    # just draw the original text, no translation
    array_raw = img_array
arraytoimg = Image.fromarray(array_raw)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s