Linux下python matplotlib.pyplot在图像上显示中文的问题(faster-rcnn中实现)
之前用py-faster-rcnn训练了一个车牌检测模型,然后对检测出来的车牌进行识别,由于我国的车牌第一个一般为汉字,在图像上显示汉字时,出现很多问题,乱码、汉字变方框等,后来在网上看了很多办法才解决,下面把解决过程记录一下。
以py-faster-rcnn的demo.py代码为基础,我在demo.py中的修改如下:
(1)指定默认编码:
- import caffe, os, sys, cv2
- reload(sys)
- sys.setdefaultencoding('utf-8')
- def vis_detections(im, class_name, dets, thresh=0.5):
- """Draw detected bounding boxes."""
- inds = np.where(dets[:, -1] >= thresh)[0]
- if len(inds) == 0:
- return
- im = im[:, :, (2, 1, 0)]
- zhfont = matplotlib.font_manager.FontProperties(fname="/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf") #字体
- fig, ax = plt.subplots(figsize=(12, 12))
- ax.imshow(im, aspect='equal')
上面的zhfont就是设置的中文字体,由于系统的原因,这个路径不一定相同,所以,用下面的命令确定你的中文字体路径:
(3)添加参数
还是vis_detections()这个函数,修改:
- ax.text(bbox[0], bbox[1] - 2,
- '{:s}'.format(s),
- bbox=dict(facecolor='blue', alpha=0.5),
- fontsize=14, color='white', fontproperties = zhfont)
那个s就是识别的结果(有中文),color后面添加fontproperties = zhfont
这样,就可以在图像上显示中文了,效果如下: