在目标检测中,当需要把所有目标框画在图像上时,需要利用到字典进行处理。也就是说当同一个标签对应的多个目标时,以标签作为键创建一个字典,对应的多个目标框作为值,如何在同一个键上追加多个值用下面代码实现。
label_path = r'.\label_2\000007.txt'
image_path = r'.\image\000007.png'
# 读取标签
target = {}
with open(label_path, 'r') as f:
while True:
lines = f.readline() # 读取每行
if not lines:
break
tmp= lines.split()
value = tmp[0] # label
coordinate = [float(i) for i in tmp[4:8]] # 每个目标的坐标
if value not in target.keys():
target[value] = [coordinate]
else:
target[value].append(coordinate) # 同类目标的坐标作为一个值
如何将其画出来呢?
# 读取图像
image = cv2.imread(image_path, cv2.COLOR_BGR2RGB)
# 图像显示
fig = plt.figure()
plt.imshow(image)
for k in target.keys():
values = target[k] # 获得对应标签的值
for v in values:
xy = (v[0], v[1]) # 左上角坐标
height = v[3] -v[1]
width = v[2] - v[0]
ax = fig.add_subplot(1, 1, 1)
rect = plt.Rectangle(xy, width, height, fill=False, edgecolor = 'red',linewidth=2)
ax.add_patch(rect)
plt.show()
结果如下: