python opencv 显示中文
时间: 2024-01-06 08:25:58 浏览: 101
要在Python的OpenCV中显示中文,可以按照以下步骤进行操作:
1. 首先,确保你已经安装了OpenCV库。如果没有安装,可以使用以下命令安装:
```shell
pip install opencv-python
pip install opencv-contrib-python
```
2. 然后,你需要下载并安装支持中文的字体文件。你可以从互联网上下载适合你的字体文件,例如"SimHei.ttf"。
3. 在你的Python代码中,导入所需的库并加载字体文件:
```python
import cv2
import numpy as np
from PIL import ImageFont, ImageDraw, Image
# 加载字体文件
font_path = 'path/to/your/font/SimHei.ttf'
font = ImageFont.truetype(font_path, size=20)
```
4. 创建一个空白图像,并使用PIL库将其转换为OpenCV图像:
```python
# 创建一个空白图像
image = np.zeros((300, 500, 3), dtype=np.uint8)
image.fill(255)
# 将图像转换为PIL图像
pil_image = Image.fromarray(image)
draw = ImageDraw.Draw(pil_image)
```
5. 使用PIL库的`text`方法在图像上绘制中文文本:
```python
# 绘制中文文本
text = '你好,世界!'
text_size = draw.textsize(text, font=font)
text_position = ((image.shape[1] - text_size[0]) // 2, (image.shape[0] - text_size[1]) // 2)
draw.text(text_position, text, font=font, fill=(0, 0, 0))
```
6. 最后,将PIL图像转换回OpenCV图像并显示:
```python
# 将PIL图像转换为OpenCV图像
cv_image = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
# 显示图像
cv2.imshow('Image', cv_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这样,你就可以在OpenCV中显示中文了。
阅读全文
相关推荐














