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)
|