opencv在图像上添加中文
时间: 2023-11-19 18:06:04 浏览: 80
要在图像上添加中文文字,你可以使用OpenCV和Python中的中文字体文件。下面是一个示例代码,演示了如何在图像上添加中文文字:
```python
import cv2
import numpy as np
from PIL import ImageFont, ImageDraw, Image
# 读取图像
image = cv2.imread("image.jpg")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image_pil = Image.fromarray(image)
# 转换为PIL的ImageDraw对象
draw = ImageDraw.Draw(image_pil)
# 字体文件路径
font_path = "font.ttf"
# 字体大小
font_size = 30
# 中文文字内容
text = "中文文字"
# 加载中文字体文件
font = ImageFont.truetype(font_path, font_size)
# 文字颜色
text_color = (255, 0, 0)
# 获取文字尺寸
text_width, text_height = draw.textsize(text, font=font)
# 文字位置
x = (image.shape[1] - text_width) // 2
y = (image.shape[0] - text_height) // 2
# 在图像上绘制中文文字
draw.text((x, y), text, font=font, fill=text_color)
# 转换回OpenCV格式的图像
image_with_text = np.array(image_pil)
image_with_text = cv2.cvtColor(image_with_text, cv2.COLOR_RGB2BGR)
# 显示图像
cv2.imshow("Image with Text", image_with_text)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在这个示例中,我们首先使用OpenCV读取了图像(假设为"image.jpg"),然后将图像转换为PIL的Image格式,这样就可以使用PIL库中的ImageDraw对象进行绘制。接下来,我们定义了要添加的中文文字内容、字体文件路径和字体大小。然后,我们使用ImageFont.truetype函数加载中文字体文件,并使用draw.textsize函数获取文字的尺寸。接着,我们计算了文字的位置,并使用draw.text函数将中文文字绘制在图像上。最后,我们将绘制完成的图像转换回OpenCV格式,并显示出来。
请确保你已经安装了Pillow库(pip install Pillow)并准备了一张图像和一个中文字体文件。根据需要,你可以调整文字的内容、字体、大小和颜色以实现更多样化的效果。