Home  >  Article  >  Backend Development  >  How to add text to pictures in python

How to add text to pictures in python

(*-*)浩
(*-*)浩Original
2019-06-29 11:18:176586browse

This article mainly introduces how to add text at a specified position on the picture through Python, mainly using two libraries, OpenCV and PIL.

How to add text to pictures in python

Install OpenCV (Recommended learning: Python video tutorial)

pip install opencv-python

Use the putText method to implement Add text to the specified position of the image

putText(img, text, org, fontFace, fontScale, color, thickness=None, lineType=None, bottomLeftOrigin=None)

img: The image array to be operated

text: The text that needs to be added to the image

fontFace: Font style setting

fontScale: Font size setting

color: Font color setting

thickness: Font thickness setting

import cv2

#加载背景图片
bk_img = cv2.imread("background.jpg")
#在图片上添加文字信息
cv2.putText(bk_img,"Hello World", (100,300), cv2.FONT_HERSHEY_SIMPLEX, 
0.7,(255,255,255), 1, cv2.LINE_AA)
#显示图片
cv2.imshow("add_text",bk_img)
cv2.waitKey()
#保存图片
cv2.imwrite("add_text.jpg",bk_img)

When using the putText method to add text to an image, Chinese characters cannot be added directly and font files cannot be imported. Next, we use another library PIL to solve this problem.

import cv2
from PIL import ImageFont, ImageDraw, Image
import numpy as np

bk_img = cv2.imread("background.jpg")
#设置需要显示的字体
fontpath = "font/simsun.ttc"
font = ImageFont.truetype(fontpath, 32)
img_pil = Image.fromarray(bk_img)
draw = ImageDraw.Draw(img_pil)
#绘制文字信息
draw.text((100, 300),  "Hello World", font = font, fill = (255, 255, 255))
draw.text((100, 350),  "你好", font = font, fill = (255, 255, 255))
bk_img = np.array(img_pil)

cv2.imshow("add_text",bk_img)
cv2.waitKey()
cv2.imwrite("add_text.jpg",bk_img)

For more Python-related technical articles, please visit the Python Tutorial column to learn!

The above is the detailed content of How to add text to pictures in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn