OpenCV的puttext是用来打印文字到图片上的,但是不支持中文,网上有方法:
https://blog.csdn.net/wyx100/article/details/75579581
以下介绍通过freetype再转换成opencv的方法。
Freetype可以方便写中文等UTF字体。
Python下载freetype-py,网址是:https://pypi.org/project/freetype-py/#files。
直接执行命令:python setup build / python setup install就可以了。
测试一下:
import freetype
face = freetype.Face('C:/Windows/Fonts/simkai.ttf')
face.set_char_size(48*64)
face.load_char('好')
bitmap = face.glyph.bitmap
print(bitmap.buffer)
打印出:
OK。
以下用OpenCV显示出来。
# -*- coding: utf-8 -*-
# http://blog.csdn.net/zizi7/article/details/70145150
'''
##################################################
# tools #
#------------------------------------------------#
# draw chinese text using freetype on python3.7 #
# 2020-04-12 #
##################################################
'''
import numpy as np
import freetype
import copy
import pdb
class put_chinese_text(object):
def __init__(self, ttf):
self._face = freetype.Face(ttf)
def draw_text(self, image, pos, text, text_size, text_color):
'''
draw chinese(or not) text with ttf
:param image: image(numpy.ndarray) to draw text
:param pos: where to draw text
:param text: the context, for chinese should be unicode type
:param text_size: text size
:param text_color:text color
:return: image
'''
self._face.set_char_size(text_size * 64)
metrics = self._face.size
ascender = metrics.ascender/64.0
#descender = metrics.descender/64.0
#height = metrics.height/64.0
#linegap = height - ascender + descender
ypos = int(ascender)
#if not isinstance(text, unicode):
# text = text.decode('utf-8')
img = self.draw_string(image, pos[0], pos[1]+ypos, text, text_color)
return img
def draw_string(self, img, x_pos, y_pos, text, color):
'''
draw string
:param x_pos: text x-postion on img
:param y_pos: text y-postion on img
:param text: text (unicode)
:param color: text color
:return: image
'''
prev_char = 0
pen = freetype.Vector()
pen.x = x_pos << 6 # div 64
pen.y = y_pos <> 6
y_pos = pen.y >> 6
cols = bitmap.width
rows = bitmap.rows
glyph_pixels = bitmap.buffer
for row in range(rows):
for col in range(cols):
if glyph_pixels[row*cols + col] != 0:
img[y_pos + row][x_pos + col][0] = color[0]
img[y_pos + row][x_pos + col][1] = color[1]
img[y_pos + row][x_pos + col][2] = color[2]
if __name__ == '__main__':
# just for test
import cv2
line = '美美的'
#img = np.zeros([300,300,3])
img = cv2.imread('c:/pic/lena.jpg', cv2.IMREAD_COLOR)
color_ = (0,0,255) # Green
pos = (30, 30)
text_size = 50
#ft = put_chinese_text('wqy-zenhei.ttc')
ft = put_chinese_text('C:/Windows/Fonts/simkai.ttf')
image = ft.draw_text(img, pos, line, text_size, color_)
cv2.imshow('freetype', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
效果如开头所示。
多谢,美。
作者:islinyoubiao