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 (https://jitheshkuyyalil.com)
Date  : May 29, 2019
"""
from PIL import Image, ImageDraw, ImageFont
import numpy as np

img = Image.new("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
array_raw.setflags(write=1)
# 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
else:
    # just draw the original text, no translation
    array_raw = img_array
arraytoimg = Image.fromarray(array_raw)
arraytoimg.show()

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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