OpenCV adds Chinese - (5)

OpenCV's method of adding text, putText(...), is no problem to add English, but if you want to add Chinese, there will be "???" garbled characters, which need special treatment.

The following provides a packaged (code) method for OpenCV to add Chinese.

past catalog

"OpenCV Environment Construction (1)"

"Picture face detection - OpenCV version (2)"

"Video face detection - OpenCV version (3)"

"Picture face detection - Dlib version (4)"

Effect preview

Realize ideas

Using PIL's picture drawing to add Chinese, you can specify the font file, which means that the Chinese output can be achieved using PIL.

Once you have an idea, the next job is easy.

  1. Convert OpenCV image format to PIL image format;
  2. Use PIL to draw text;
  3. Convert PIL image format to OpenCV image format;

code decomposition

Convert OpenCV image to PIL image format

img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))

Drawing text with PIL

draw = ImageDraw.Draw(img)
fontText = ImageFont.truetype("font/simsun.ttc", textSize, encoding="utf-8")
draw.text((left, top), "文字内容", textColor, font=fontText)

The font file is: simsun.ttc, Windows can be found under C:\Windows\Fonts.

Convert PIL image format to OpenCV image format

cv2.cvtColor(numpy.asarray(img), cv2.COLOR_RGB2BGR)

full code

Encapsulated complete method

#coding=utf-8
#中文乱码处理

import cv2
import numpy
from PIL import Image, ImageDraw, ImageFont

def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20):
    if (isinstance(img, numpy.ndarray)):  #判断是否OpenCV图片类型
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    draw = ImageDraw.Draw(img)
    fontText = ImageFont.truetype(
        "font/simsun.ttc", textSize, encoding="utf-8")
    draw.text((left, top), text, textColor, font=fontText)
    return cv2.cvtColor(numpy.asarray(img), cv2.COLOR_RGB2BGR)

code call

img = cv2ImgAddText(img, "大家好,我是星爷", 140, 60, (255, 255, 0), 20)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325340808&siteId=291194637