背景: opencv內(nèi)置的cv2.puttext函數(shù)不能顯示中文字符,嘗試了下列方法:
(1)cv2.freetype。沒(méi)有這個(gè)庫(kù);
(2)opencv無(wú)法導(dǎo)入中文字體庫(kù);
(3)卸載opencv-python,安裝opencv-python-headless, opencv- contrib-python文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-643370.html
方法: 使用PIL庫(kù)作為中轉(zhuǎn)文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-643370.html
- 下載中文字體庫(kù)https://github.com/StellarCN/scp_zh/blob/master/fonts/SimHei.ttf
- 使用下述代碼繪制中文字符
def cv2AddChineseText(img, text, position, textColor=(0, 255, 0), textSize=30):
"""
img:opecv格式
cv2顯示中文字符
"""
if (isinstance(img, np.ndarray)): # 判斷是否OpenCV圖片類型
img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
# 創(chuàng)建一個(gè)可以在給定圖像上繪圖的對(duì)象
draw = ImageDraw.Draw(img)
# 字體的格式
fontStyle = ImageFont.truetype(
"SimHei.ttf", textSize, encoding="utf-8")
# 繪制文本
draw.text(position, text, textColor, font=fontStyle)
# 轉(zhuǎn)換回OpenCV格式
return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
到了這里,關(guān)于解決opencv, cv2.puttext函數(shù)無(wú)法顯示中文字符的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!