我在Python中使用自定义字体将文本绘制到numpy阵列图像上.目前我正在将图像转换为PIL,绘制文本然后转换回numpy数组.
import numpy as np
import cv2
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
char_image = np.zeros((200, 300, 3), np.uint8)
# convert to pillow image
pillowImage = Image.fromarray(char_image)
draw = ImageDraw.Draw(pillowImage)
# add chars to image
font = ImageFont.truetype("arial.ttf", 32)
draw.text((50, 50), 'ABC', (255, 255, 255), font=font)
# convert back to numpy array
char_image = np.array(pillowImage, np.uint8)
# show image on screen
cv2.imshow('myImage', char_image)
cv2.waitKey(0)
无论如何都要在给定的角度上绘制文本,即. 33度?
绘制文本后旋转图像不是一种选择
解决方法:
使用matplotlib,首先可视化数组并在其上绘制,从图中获取原始数据.
亲:这两个工具都是相当高的水平,让你处理过程的许多细节. ax.annotate()
为绘制和设置字体属性的位置和方式提供了灵活性,plt.matshow()
提供了灵活性,使您可以处理阵列可视化的各个方面.
import matplotlib.pyplot as plt
import scipy as sp
# make Data array to draw in
M = sp.zeros((500,500))
dpi = 300.0
# create a frameless mpl figure
fig, axes = plt.subplots(figsize=(M.shape[0]/dpi,M.shape[1]/dpi),dpi=dpi)
axes.axis('off')
fig.subplots_adjust(bottom=0,top=1.0,left=0,right=1)
axes.matshow(M,cmap='gray')
# set custom font
import matplotlib.font_manager as fm
ttf_fname = '/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-B.ttf'
prop = fm.FontProperties(fname=ttf_fname)
# annotate something
axes.annotate('ABC',xy=(250,250),rotation=45,fontproperties=prop,color='white')
# get fig image data and read it back to numpy array
fig.canvas.draw()
w,h = fig.canvas.get_width_height()
Imvals = sp.fromstring(fig.canvas.tostring_rgb(),dtype='uint8')
ImArray = Imvals.reshape((w,h,3))