-
大小: 12.94MB文件类型: .zip金币: 1下载: 0 次发布日期: 2023-06-26
- 语言: Python
- 标签:
资源简介
python+freetype+opencv 中文(汉字)显示 项目完整源代码
在图片上显示中文(汉字),分享大家,别忘了好评
代码片段和文件信息
# -*- coding: utf-8 -*-
# http://blog.csdn.net/zizi7/article/details/70145150
‘‘‘
##################################################
# tools #
#------------------------------------------------#
# draw chinese text using freetype on python2.x # #
# 2017.4.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
hscale = 1.0
matrix = freetype.Matrix(int(hscale)*0x10000L int(0.2*0x10000L)\
int(0.0*0x10000L) int(1.1*0x10000L))
cur_pen = freetype.Vector()
pen_translate = freetype.Vector()
image = copy.deepcopy(img)
for cur_char in text:
self._face.set_transform(matrix pen_translate)
self._face.load_char(cur_char)
kerning = self._face.get_kerning(prev_char cur_char)
pen.x += kerning.x
slot = self._face.glyph
bitmap = slot.bitmap
cur_pen.x = pen.x
cur_pen.y = pen.y - slot.bitmap_top * 64
self.draw_ft_bitmap(image bitmap cur_pen color)
pen.x += slot.advance.x
prev_char = cur_char
return image
def draw_ft_bitmap(self img bitmap pen color):
‘‘‘
draw each char
:param bitmap: bitmap
:param pen: pen
:param c
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
目录 0 2017-07-21 00:35 hzTest\
目录 0 2017-07-21 00:35 hzTest\.idea\
文件 459 2017-07-21 00:34 hzTest\.idea\hzTest.iml
目录 0 2017-07-21 00:33 hzTest\.idea\inspectionProfiles\
文件 228 2017-07-21 00:33 hzTest\.idea\inspectionProfiles\profiles_settings.xm
文件 226 2017-07-21 00:33 hzTest\.idea\misc.xm
文件 264 2017-07-21 00:33 hzTest\.idea\modules.xm
文件 22301 2017-07-21 00:35 hzTest\.idea\workspace.xm
文件 3954 2017-07-21 00:34 hzTest\ft2.py
文件 4137 2017-07-21 00:35 hzTest\ft2.pyc
文件 384 2017-07-21 00:35 hzTest\hzTest.py
文件 21767952 2009-06-11 05:25 hzTest\msyh.ttf
目录 0 2017-07-21 00:35 hzTest\pic\
文件 9886 2017-07-12 12:58 hzTest\pic\lena.jpg
评论
共有 条评论