Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write text over an image, and overlay another image on it, in Python?

I need to put some text over a PNG image in Python, I need to put another image too over the first one.

So I'll have a base image (the same for every image created), a logo to put over it in the upper left corner, and a text all over the image (non-specific font, I just need to set the font size).

Could I use PIL, or another Library?

I searched over StackOverflow and Google too, but I could not find tips on how to do this.

Thanks.

like image 920
redmarv Avatar asked Nov 16 '11 16:11

redmarv


People also ask

How do you overlay an image on another image in Python?

Firstly we opened the primary image and saved its image object into variable img1. Then we opened the image that would be used as an overlay and saved its image object into variable img2. Then we called the paste method to overlay/paste the passed image on img1.

How do I overlay a text on an image?

On the Insert tab, in the Text group, click WordArt, click the style of text you want, and then type your text. Click the outside edge of the WordArt to select it, drag the text over your photo and then, if you want to, rotate the text to the angle that works best for your photo.


2 Answers

I think opencv is easier to use:

import cv2
import numpy as np
import matplotlib.pyplot as plt
image = cv2.imread('xxx.png')  
texted_image =cv2.putText(img=np.copy(image), text="hello", org=(200,200),fontFace=3, fontScale=3, color=(0,0,255), thickness=5)
plt.imshow(texted_image)
plt.show()

Note that the original image may be changed, so I add np.copy to protect it. More details on the function is http://docs.opencv.org/2.4.8/modules/core/doc/drawing_functions.html?highlight=puttext#cv2.putText

The fontFace can be referred to https://codeyarns.com/2015/03/11/fonts-in-opencv/

like image 149
Yuchao Jiang Avatar answered Oct 23 '22 09:10

Yuchao Jiang


PIL can do it:

from PIL import Image, ImageFont, ImageDraw
font = ImageFont.truetype("/usr/share/fonts/dejavu/DejaVuSans.ttf", 25)
img = Image.new("RGBA", (200,200), (120,20,20))
draw = ImageDraw.Draw(img)
draw.text((0,0), "This is a test", (255,255,0), font=font)
img.save("a_test.png")

The only error that can occur is not to find the font. In this case you must change the code line:

font = ImageFont.truetype("/usr/share/fonts/dejavu/DejaVuSans.ttf",25)

Source: http://python-catalin.blogspot.com/2010/06/add-text-on-image-with-pil-module.html

like image 42
Lou Franco Avatar answered Oct 23 '22 10:10

Lou Franco