本文主要是在推理detect阶段,预测的图片或视频中没有标签的数量统计
在 detect.py中的第171行(大家看自己位置,我这里是大概位置)加入这行代码
cv2.putText(im0, f"{n} " + 'person', (5, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 0, 255), 2)
修改后的 11行和28行29行
if len(det):
# Rescale boxes from img_size to im0 size
det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
# Print results
for c in det[:, -1].unique():
n = (det[:, -1] == c).sum() # detections per class
print(n)
s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
cv2.putText(im0, f"{n} " + 'person', (5, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 0, 255), 2)
# Write results
for *xyxy, conf, cls in reversed(det):
if save_txt: # Write to file
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
with open(txt_path + '.txt', 'a') as f:
f.write(('%g ' * len(line)).rstrip() % line + '\n')
if save_img or save_crop or view_img: # Add bbox to image
c = int(cls) # integer class
label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
annotator.box_label(xyxy, label, color=colors(c, True))
if save_crop:
save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
# 注释 这里加入else 是为了输出预测框为0时的结果
else:
cv2.putText(im0, '0 person', (5, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 0, 255), 2)
如果想要 根据预测框的数量 来进行分等级 加入6-15行
# Print results
for c in det[:, -1].unique():
n = (det[:, -1] == c).sum() # detections per class
s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
# 根据预测框数量进行等级分类
if (int(f"{n}") < 10):
strr = "111" # 小于10个框等级111
elif (int(f"{n}") > 10 and int(f"{n}") < 20):
strr = "222" # 小于20个小于10个 等级222
else:
strr = "333" # 大于20个 等级333
cv2.putText(im0, f"{n} " + 'person' + strr + (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
print(s)