OpenCV Python窗口显示中文乱码

OpenCV是一个功能强大的计算机视觉库,它提供了许多图像处理和计算机视觉算法的实现。然而,在使用OpenCV进行图像处理时,我们有时会遇到窗口显示中文乱码的问题。这是因为OpenCV默认使用的字体不支持中文字符。在本文中,我们将介绍如何在OpenCV Python窗口中显示中文,并提供相应的代码示例。

安装所需的库

在开始之前,我们需要安装以下库:

  1. OpenCV:可以使用pip install opencv-python命令安装OpenCV。
  2. freetype-py:可以使用pip install freetype-py命令安装freetype-py。

加载中文字体

为了在OpenCV窗口中正确显示中文,我们需要加载一个支持中文字符的字体。在本文中,我们将使用"SimHei.ttf"字体。你可以在互联网上找到并下载这个字体文件。

编写代码

首先,我们需要导入所需的库,并加载"SimHei.ttf"字体:

import cv2
import freetype

font_path = "SimHei.ttf"
face = freetype.Face(font_path)

接下来,我们需要创建一个空白图像,并在图像上绘制中文字符:

width, height = 800, 600
image = np.zeros((height, width, 3), dtype=np.uint8)
image.fill(255)  # 设置背景为白色

text = "你好,世界!"
font_size = 36
x, y = 100, 200

face.set_char_size(font_size * 64)
pen = freetype.Pen()
pen.color = (0, 0, 0)  # 设置字体颜色为黑色

pen.x = x
pen.y = y

for char in text:
    face.load_char(char)
    bitmap = face.glyph.bitmap
    image[y:y + bitmap.rows, x:x + bitmap.width] |= np.array(bitmap.buffer.reshape(bitmap.rows, bitmap.width), dtype=np.uint8)
    pen.x += face.glyph.advance.x // 64

最后,我们可以使用OpenCV的窗口函数显示图像:

cv2.imshow("中文文本", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

完整代码示例

import cv2
import freetype
import numpy as np

font_path = "SimHei.ttf"
face = freetype.Face(font_path)

width, height = 800, 600
image = np.zeros((height, width, 3), dtype=np.uint8)
image.fill(255)  # 设置背景为白色

text = "你好,世界!"
font_size = 36
x, y = 100, 200

face.set_char_size(font_size * 64)
pen = freetype.Pen()
pen.color = (0, 0, 0)  # 设置字体颜色为黑色

pen.x = x
pen.y = y

for char in text:
    face.load_char(char)
    bitmap = face.glyph.bitmap
    image[y:y + bitmap.rows, x:x + bitmap.width] |= np.array(bitmap.buffer.reshape(bitmap.rows, bitmap.width), dtype=np.uint8)
    pen.x += face.glyph.advance.x // 64

cv2.imshow("中文文本", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

总结

通过加载支持中文字符的字体,我们可以在OpenCV Python窗口中正确显示中文。本文提供了一个简单的代码示例,演示了如何在OpenCV窗口中绘制中文文本。你可以根据自己的需求进行修改和扩展。

希望本文能够帮助你解决OpenCV Python窗口显示中文乱码的问题。如果你有任何问题或疑问,请随时向我们提问。