1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from PIL import ImageDraw,ImageFont,Image
def img_writer(text_size,xy,text,text_color,fontStyle,img):
draw = ImageDraw.Draw(img)
# 字体的格式 这里的SimHei.ttf需要有这个字体
fontStyle = ImageFont.truetype(fontStyle, text_size, encoding='utff8')
# 绘制文本
draw.text(xy, text, text_color, font=fontStyle)

if __name__ == '__main__':
text_size = 50 # 字体大小
xy = (56, 1700) # 起始位置
data = 'Menhenra酱,卡哇伊!' # 内容
text_color = (26, 42, 44) # 字体颜色
fontStyle = f'PingFang Bold.ttf' # 字体位置
img = Image.open('图片路径')
img_writer(text_size, xy, data, text_color, fontStyle, img)

标识符 标识符
FONT_HERSHEY_SIMPLEX = 0 !< normal size sans-serif font 普通大小无衬线字体
FONT_HERSHEY_PLAIN = 1 !< small size sans-serif font 小号无衬线字体
FONT_HERSHEY_DUPLEX = 2 !< normal size sans-serif font (more complex than FONT_HERSHEY_SIMPLEX) 普通大小无衬线字体
FONT_HERSHEY_COMPLEX = 3 !< normal size serif font 普通大小无衬线字体比 FONT_HERSHEY_DUPLEX 更复杂
FONT_HERSHEY_TRIPLEX = 4 !< normal size serif font (more complex than FONT_HERSHEY_COMPLEX 普通大小无衬字体,比 FONT_HERSHEY_COMPLEX 更复杂
FONT_HERSHEY_COMPLEX_SMALL = 5 !< smaller version of FONT_HERSHEY_COMPLEX小号版本的 FONT_HERSHEY_COMPLEX
FONT_HERSHEY_SCRIPT_SIMPLEX = 6 !< hand-writing style font 手写字体
FONT_HERSHEY_SCRIPT_COMPLEX = 7 !< more complex variant of FONT_HERSHEY_SCRIPT_SIMPLEX比 FONT_HERSHEY_SCRIPT_SIMPLEX 更复杂的变体
FONT_ITALIC = 16 !< flag for italic font
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont

def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20):
if (isinstance(img, np.ndarray)): # 判断是否OpenCV图片类型
img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
# 创建一个可以在给定图像上绘图的对象
draw = ImageDraw.Draw(img)
# 字体的格式
fontStyle = ImageFont.truetype(
"simsun.ttc", textSize, encoding="utf-8")
# 绘制文本
draw.text((left, top), text, textColor, font=fontStyle)
# 转换回OpenCV格式
return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)

img = cv2ImgAddText(cv2.imread('img1.jpg'), "hello中文", 10, 65, (0, 0 , 139), 20)
cv2.imshow('show', img)
cv2.waitkey(0)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def put_text(text,img,w=0,h=50):
textColor = (255,0,0)
# 转PIL
img = Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))
# 创建一个可以在图像绘图的对象
draw = ImageDraw.Draw(img)
# 字体格式
fonStyle = ImageFont.truetype(
"simsun.ttc",
size=20,
encoding="utf-8"
)
# 绘制文本
draw.text((w,h),text,textColor,font=fonStyle)
# 转回opencv的BGR格式
return cv2.cvtColor(np.asarray(img),cv2.COLOR_RGB2BGR)