解决在 yolov8 训练自己的数据集时,matplotlib 中文乱码问题

在 yolov8 训练自己的数据集时,如果 class 字典使用了中文,则在训练过程中会出现形如下面的警告:

1
2
C:\Users\woodwhales\AppData\Roaming\Python\Python311\site-packages\ultralytics\utils\metrics.py:427: UserWarning: Glyph 26222 (\N{CJK UNIFIED IDEOGRAPH-666E}) missing from current font.
fig.savefig(plot_fname, dpi=250)

步骤1:找到 matplotlib 的字体文件目录

执行下述 python 脚本:

1
2
import matplotlib
print(matplotlib.matplotlib_fname())

执行上述脚本后,可以看到 matplotlibrc 文件的所在目录:

1
C:\programs\anaconda3\Lib\site-packages\matplotlib\mpl-data\matplotlibrc

步骤2:将中文字体保存到 matplotlib

在步骤1 的基础上,可以得到 matplotlib 的文件根目录是:C:\programs\anaconda3\Lib\site-packages\matplotlib\mpl-data,那么字体文件目录就在 C:\programs\anaconda3\Lib\site-packages\matplotlib\mpl-data\fonts\ttf

在 ttf 文件目录中拷贝中文字体,格式要求为 ttf,笔者使用的是微软雅黑,可以在这里下载:Microsoft YaHei.zip

windows系统中都有微软雅黑,文件目录为:C:\Windows\Fonts,但是其格式为 ttc,可以使用这个网站在线转换为 ttf:https://transfonter.org/ttc-unpack

步骤3:清除 matplotlib 缓存

执行下述 python 脚本:

1
2
3
4
import shutil
import matplotlib

shutil.rmtree(matplotlib.get_cachedir())

步骤4:检查中文字体是否生效

执行下述 python 脚本:

1
2
3
import matplotlib.font_manager

print([f for f in matplotlib.font_manager.fontManager.ttflist if 'Microsoft YaHei' in f.name])

可以得到对应字体信息:

1
[FontEntry(fname='C:\\programs\\anaconda3\\Lib\\site-packages\\matplotlib\\mpl-data\\fonts\\ttf\\Microsoft YaHei.ttf', name='Microsoft YaHei', style='normal', variant='normal', weight=400, stretch='normal', size='scalable'), FontEntry(fname='C:\\Windows\\Fonts\\msyhbd.ttc', name='Microsoft YaHei', style='normal', variant='normal', weight=700, stretch='normal', size='scalable'), FontEntry(fname='C:\\Windows\\Fonts\\msyh.ttc', name='Microsoft YaHei', style='normal', variant='normal', weight=400, stretch='normal', size='scalable'), FontEntry(fname='C:\\Windows\\Fonts\\msyhl.ttc', name='Microsoft YaHei', style='normal', variant='normal', weight=290, stretch='normal', size='scalable')]

步骤5:matplotlib 使用中文字体

在训练集脚本的最开始,增加如下代码:

1
2
3
import matplotlib

matplotlib.rcParams['font.family'] = ['Microsoft YaHei']
updated updated 2024-04-22 2024-04-22
本文结束感谢阅读

本文标题:解决在 yolov8 训练自己的数据集时,matplotlib 中文乱码问题

本文作者:

微信公号:木鲸鱼 | woodwhales

原始链接:https://woodwhales.cn/2024/03/20/099/099/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%