OpenCV 默認(rèn)情況下不支持中文顯示,因此我們需要使用 PIL 庫來繪制中文,并將繪制的結(jié)果轉(zhuǎn)換為 OpenCV 可以顯示的格式。
首先,我們使用?PIL 庫中的 ImageFont、ImageDraw 和 Image 類,以及 NumPy 和 OpenCV 庫。你需要先安裝這些庫,然后將代碼中的 fontpath
修改為你自己的字體文件路徑。
代碼首先創(chuàng)建一個(gè)黑色的圖像,然后使用 PIL 庫定義中文字體和大小。我們使用 Image.fromarray
將 NumPy 數(shù)組轉(zhuǎn)換為 PIL Image 對(duì)象,然后使用 ImageDraw 在圖像上繪制中文。最后,我們將 PIL Image 對(duì)象轉(zhuǎn)換回 NumPy 數(shù)組,并使用 OpenCV 的 imshow
方法顯示圖像。
代碼如下
import cv2
import numpy as np
from PIL import ImageFont, ImageDraw, Image
# 創(chuàng)建一個(gè)黑色的圖像
img = np.zeros((512,512,3), np.uint8)
# 使用PIL庫定義中文字體,大小為40
fontpath = "path/to/font.ttf"
font = ImageFont.truetype(fontpath, 40)
# 在圖像上繪制中文
img_pil = Image.fromarray(img)
draw = ImageDraw.Draw(img_pil)
text = "你好,世界!"
draw.text((100, 200), text, font=font, fill=(255, 255, 255, 0))
img = np.array(img_pil)文章來源:http://www.zghlxwxcb.cn/news/detail-657886.html
# 顯示圖像
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
?文章來源地址http://www.zghlxwxcb.cn/news/detail-657886.html
到了這里,關(guān)于opencv圖像中顯示中文的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!