如何正确使用`cv2.putText`在图像上绘制中文文本? (Python + OpenCV) [英] How to draw Chinese text on the image using `cv2.putText`correctly? (Python+OpenCV)

查看:1131
本文介绍了如何正确使用`cv2.putText`在图像上绘制中文文本? (Python + OpenCV)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用python cv2(window10,python2.7)在图像中编写文本,当文本为英文时它可以工作,但是当我使用中文文本时,它在图像中编写混乱的代码.

I use python cv2(window10, python2.7) to write text in image, when the text is English it works, but when I use Chinese text it write messy code in the image.

下面是我的代码:

# coding=utf-8
import cv2
import numpy as np

text = "Hello world"   # just work
# text = "内容理解团队"  # messy text in the image

cv2.putText(img, text,
            cord,
            font,
            fontScale,
            fontColor,
            lineType)

# Display the image
cv2.imshow("img", img)

cv2.waitKey(0)
cv2.destroyAllWindows()

text = "Hello world" # just work时,下面是输出图像:

When text = "Hello world" # just work, below is the output image:

text = "内容理解团队" # Chinese text, draw messy text in the image时,下面是输出图像:

When text = "内容理解团队" # Chinese text, draw messy text in the image, below is the output image:

怎么了? opencv putText不支持其他语言的文字吗?

What's wrong? Does opencv putText don't support other language text?

推荐答案

据我所知,cv2.putText不支持no-ascii字符. Try to use PIL to draw NO-ASCII(such Chinese) on the image.

The cv2.putText don't support no-ascii char in my knowledge. Try to use PIL to draw NO-ASCII(such Chinese) on the image.

import numpy as np
from PIL import ImageFont, ImageDraw, Image
import cv2
import time

## Make canvas and set the color
img = np.zeros((200,400,3),np.uint8)
b,g,r,a = 0,255,0,0

## Use cv2.FONT_HERSHEY_XXX to write English.
text = time.strftime("%Y/%m/%d %H:%M:%S %Z", time.localtime()) 
cv2.putText(img,  text, (50,50), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (b,g,r), 1, cv2.LINE_AA)


## Use simsum.ttc to write Chinese.
fontpath = "./simsun.ttc" # <== 这里是宋体路径 
font = ImageFont.truetype(fontpath, 32)
img_pil = Image.fromarray(img)
draw = ImageDraw.Draw(img_pil)
draw.text((50, 80),  "端午节就要到了。。。", font = font, fill = (b, g, r, a))
img = np.array(img_pil)

cv2.putText(img,  "--- by Silencer", (200,150), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (b,g,r), 1, cv2.LINE_AA)


## Display 
cv2.imshow("res", img);cv2.waitKey();cv2.destroyAllWindows()
#cv2.imwrite("res.png", img)

请参阅我的另一个答案:

Refer to my another answer:

将TrueType字体加载到OpenCV

这篇关于如何正确使用`cv2.putText`在图像上绘制中文文本? (Python + OpenCV)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆