【解决方案】使用matplotlib报错 TypeError: unsupported operand type(s) for -: ‘str’ and ‘float’
绘制柱状图时
"""
yolo格式标注文件统计
"""
import os
img_path = './images'
label_path = img_path.replace('images', 'labels')
label_names = ['car', 'chair']
label_files = os.listdir(label_path)
object_struct = {}
for name in label_files:
file_path = os.path.join(label_path, name)
with open(file_path) as f:
for f1 in f.readlines():
box = []
f1 = f1.replace('\n', '').strip().split(' ')
box = [x for x in f1]
# print(box)
cls_id = box[0]
x1 = box[1]
y1 = box[2]
x2 = box[3]
y2 = box[4]
if cls_id not in object_struct:
object_struct[cls_id] = 0
object_struct[cls_id] += 1
print(object_struct)
import matplotlib.pyplot as plt
object = []
number = []
for name_key in object_struct:
if len(label_names) != 0:
object.append(label_names[int(name_key)])
else:
object.append(name_key)
number.append(object_struct[name_key])
print(object, '\n', number)
plt.figure()
# 低版本matplotlib方法
# idx = range(len(object))
# plt.xticks(idx, object)
# plt.bar(idx, number)
# 高版本matplotlib方法
plt.bar(object, number)
plt.title('result')
plt.show()
报错以下信息:
报错原因:
轴不能用 字符串列表
解决方案:
字符串列表转化为数字列表,再把数字列表和字符串列表组合起来
使用高版本的matplotlib=3.x就不存在这个问题,matplotlib=2.x会出现这个报错
# 低版本matplotlib方法
# idx = range(len(object))
# plt.xticks(idx, object)
# plt.bar(idx, number)
# 高版本matplotlib方法
plt.bar(object, number)