一直没有找到很好的计数代码,自己做了一点尝试修改detect.py文件。
https://github.com/ultralytics/yolov5/blob/v6.1/detect.py
定位到原代码中的 # Print results,作以下修改。
还不能实现单个类内的从1到N的计数,有会的朋友请不吝赐教。
肉眼看了一下缝针的数量,8个排针+6个三角针+1个散放的针=15个,数量是欠精确的。框框实在太密集了,以至于无法判断倒底是左侧的算多了,还是右侧的算多了。
if len(det):
# Rescale boxes from img_size to im0 size
det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
Results = "Results: "
# Print results
for c in det[:, -1].unique():
n = (det[:, -1] == c).sum() # detections per class
s += '\n'+f"{n} {names[int(c)]}{'s' * (n > 1)}" # add to string
Results += '\n'+f"{n} {names[int(c)]}" # TODO 加了一个变量Results
#s += f"{n} {names[int(c)]}{'s' * (n > 1)}, +" # add to string
# 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: # TODO # 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} {(det[:, -1] == c).sum()}') # TODO 标签计数展示加在了末尾
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)
# Stream results
im0 = annotator.result()
if view_img:
cv2.imshow(str(p), im0)
cv2.waitKey(1) # 1 millisecond
# Save results (image with detections)
if save_img:
# 需用循环的方式显示多行,因为cv2.putText对换行转义符'\n'显示为'?'
y0, dy = 50, 40
for i, txt in enumerate(Results.split('\n')):
y = y0 + i * dy
#cv2.putText(im0, txt, (50, y), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 255, 0), 2, 2)
cv2.putText(im0, Results, (10, 10), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 0, 255), 3) # TODO 左上角显示检测标签和数量
原图和检测结果如下