How to add text on image in Python pillow
Pillow is a fork for the Python Imaging Library, PIL, that provides a variety of image-processing features to manipulate images and apply different filters to them. It is a powerful library that is easy to integrate with other Python libraries and frameworks. By using the pillow library, we can perform various operations on an image as follows:
Filter effects like blurring
Image enhancement, like adjusting brightness, contrast, and sharpness
Image overlay, like adding text on an image
Note: We can also add shapes on an image. Read an answer on ImageDraw() in Python pillow to learn further about it.
In this Answer, we shall enhance the image by changing its brightness, contrast, and sharpness and observe how the image changes.
What is adding text?
Adding text refers to placing a layer over an image that contains content that can be visible over the image. We can customize the color or placement of the text according to our needs. In this example, an image of a mango is composed of text.
What is RGBA?
RGBA is one of the color modes that help to specify how thw image color values are interpreted.
R | Red |
G | Green |
B | Blue |
A | Alpha |
Here Alpha stores the transparency information of the image. We can use this to control the opacity of each pixel and adjust it within the range of 0 to 255. In this case, 0 is completely transparent, and 255 is completely opaque.
Required imports
We will use the PIL library to manipulate the image and then use matplotlib to display the results once the code is executed successfully.
import matplotlib.pyplot as pltfrom PIL import Image, ImageDraw, ImageFontimport requestsfrom io import BytesIO
matplotlib: to create visualizations and plots in the Python library.PIL: computer vision library to apply operations on images.Image: to enhance the image properties that change its appearance.ImageDraw: to draw on the image, e.g., adding text.ImageFont: to access different fonts and change according to the requirement.
requests: to send the requests over the HTTP server to the website.BytesIO: to handle the binary data as an in-memory system.
Expected output
For a half-opaque text, we set the Alpha value to 128 when adding a text fill, and the obtained text is visible but translucent. On the other hand, for a completely opaque text, we set the Alpha value to 225 when adding a text fill, and the obtained text is visible but translucent.
Let's write a code that shows both text types and shows the modified images with text.
Example code
In this example, we add half opaque text and full opaque text on the image individually to observe the difference.
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw, ImageFont
import requests
from io import BytesIO
import os
import cv2
image_url = "https://images.pexels.com/photos/3390587/pexels-photo-3390587.jpeg?auto=compress&cs=tinysrgb&w=600&lazy=load"
#fetch image
response = requests.get(image_url)
image_data = BytesIO(response.content)
original_image = Image.open(image_data).convert('RGBA')
#making a blank image
text_one = Image.new('RGBA', original_image .size, (255,255,255,0))
text_two = Image.new('RGBA', original_image .size, (255,255,255,0))
#draw images
draw_one = ImageDraw.Draw(text_one)
draw_two = ImageDraw.Draw(text_two)
font_path = os.path.join(cv2.__path__[0],'qt','fonts','DejaVuSans.ttf')
text_font = ImageFont.truetype(font_path, size=128)
#draw text with the half opacity
draw_one.text((14,14), "Sea life", font=text_font, fill=(255,255,255,128))
new_imageOne = Image.alpha_composite(original_image , text_one)
# draw text with the full opacity
draw_two.text((14,14), "Sea life", font=text_font, fill=(255,255,255,255))
new_imageTwo = Image.alpha_composite(original_image , text_two)
plt.figure(figsize=(10, 5))
plt.subplots_adjust(wspace=0.4, hspace=0.1)
plt.subplot(1, 3, 1)
plt.imshow(original_image )
plt.axis('off')
plt.title('Original Image')
plt.subplot(1, 3, 2)
plt.imshow(new_imageOne)
plt.axis('off')
plt.title('Half Opacity Text')
plt.subplot(1, 3, 3)
plt.imshow(new_imageTwo)
plt.axis('off')
plt.title('Full Opacity Text')
plt.show()
Code explanation
Lines 1–6: Import the required libraries and modules.
Line 8: Store the link of the image that is to be used on
image_url. We can also use a local image file and give its exact name.Lines 11–12: Use
requestto fetch the image from the server and open it using theImage.open()method and pass the converted image to it.Line 13: Convert the image to the RGBA format, open it, and save it in the
original_imageobject.Lines 16–17: Create transparent blank images that will contain the text.
Lines 20–21: Create the drawing objects and specify the transparent blank image we want to draw on as a parameter to
Draw().Line 23: Use font from the
cv2fonts and specify its path and file. In this case, we use DejaVuSans.ttf font style.
Line 24: Use
ImageFontand set atruetypefont for the text. Pass the font path and size as a parameter.Line 27: Pass the text position, text, font, and its fill’s RGBA value as 128 inside the
text()method for the half-opaque text.Line 31: Pass the text position, text, font, and its fill’s RGBA value as 255 inside the
text()method for the completely opaque text.Lines 28,32: Use
composite()to join the original image and the corresponding transparent image on which the text is added.Lines 34–35: Specify the figure size that is to appear in the plot and assign the grid size.
Lines 37–40: Display the image using
imshow()and pass the original image to it, turn off the x-axis labels, and specify the title in thetitle().Lines 42–45: Display the image using
imshow()and pass the image with half-opaque text to it, turn off the x-axis labels, and specify the title in thetitle().Lines 47–50: Display the image using
imshow()and pass the image with completely opaque text to it, turn off the x-axis labels, and specify the title in thetitle().Line 52: Show the resultant plot.
Real-life application
There are a lot of real-life scenarios where there is a need to enhance the image. Let's take a look at a few of the scenarios where image enhancement is useful.
Common query
Can we add multiple lines of text in the same image?
Free Resources