我使用python cv2(window10,python2.7)在图像中写入文本,当文本是英文时它可以工作,但是当我使用中文文本时它会在图像中写出乱码.
以下是我的代码:
# 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()
Run Code Online (Sandbox Code Playgroud)
当text = "Hello world" # just work下面是输出图像时:
当text = "??????" # Chinese text, draw messy text in the image下面是输出图像时:
怎么了?opencv putText不支持其他语言文本吗?
Kin*_*t 金 10
据cv2.putText我所知,不支持no-ascii char.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)
Run Code Online (Sandbox Code Playgroud)
请参阅我的另一个答案:
小智 5
根据这个opencv论坛,putText只能支持一小部分ascii字符子集,不支持unicode字符,即其他符号,例如中文和阿拉伯字符。
但是,您可以尝试使用 PIL 代替,并按照此处发布的答案进行操作,看看它是否适合您。
| 归档时间: |
|
| 查看次数: |
6266 次 |
| 最近记录: |