Linux下python matplotlib.pyplot在图像上显示中文的问题(faster-rcnn中实现)

之前用py-faster-rcnn训练了一个车牌检测模型,然后对检测出来的车牌进行识别,由于我国的车牌第一个一般为汉字,在图像上显示汉字时,出现很多问题,乱码、汉字变方框等,后来在网上看了很多办法才解决,下面把解决过程记录一下。


以py-faster-rcnn的demo.py代码为基础,我在demo.py中的修改如下:

(1)指定默认编码:

[plain]  view plain  copy
  1. import caffe, os, sys, cv2  
  2. reload(sys)  
  3. sys.setdefaultencoding('utf-8')  


(2)设置中文字体:

[plain]  view plain  copy
  1. def vis_detections(im, class_name, dets, thresh=0.5):  
  2.     """Draw detected bounding boxes."""  
  3.     inds = np.where(dets[:, -1] >= thresh)[0]  
  4.     if len(inds) == 0:  
  5.         return  
  6.   
  7.     im = im[:, :, (2, 1, 0)]  
  8.     zhfont = matplotlib.font_manager.FontProperties(fname="/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf") #字体  
  9.       
  10.     fig, ax = plt.subplots(figsize=(12, 12))  
  11.     ax.imshow(im, aspect='equal')  

上面的zhfont就是设置的中文字体,由于系统的原因,这个路径不一定相同,所以,用下面的命令确定你的中文字体路径:



(3)添加参数

还是vis_detections()这个函数,修改:

[plain]  view plain  copy
  1. ax.text(bbox[0], bbox[1] - 2,  
  2.                 '{:s}'.format(s),  
  3.                 bbox=dict(facecolor='blue', alpha=0.5),  
  4.                 fontsize=14, color='white', fontproperties = zhfont)  

那个s就是识别的结果(有中文),color后面添加fontproperties = zhfont

这样,就可以在图像上显示中文了,效果如下:

猜你喜欢

转载自blog.csdn.net/hongxingabc/article/details/79494872