YOLOv5のdetecy.pyで物体検出を行うと、検出されたclassの件数が出力されます。
検出しないclassの件数を0として出力させたいのですが、どのようにしたら良いかご教示いただければと思います。
GitHubのインストラクションも確認したのですが、どこを見れば良いのかわからず、
detect.pyもにらめっこしていますが、解決できません。
アドバイスお願いします。
detect.pyの改造した部分は、後半部分で ##
を付けた部分です。
多分、変数の
- cがclass
- nが検出数
- sがc,nを併せて検出結果を示すもの
これらがlogger.infoとして表示されるのだと理解し、それをpandasにてcsvに書き出すようにしてみました。
それはそれでうまくできたのですが、検出対象外のクラスも0として出力したいわけです。
多分YOLOv5のチュートリアルを解読すればよいのだと思うのですが、チュートリアルのどこを見れば良いのかもわからず、Pythonの知識もそれほどあるわけではなく、コードを読み解くのも限界ということで質問させていただきました。
detect.pyでlogger.nfoの出力の部分について、自分で修正してみた部分を以下に示します。
# Process predictions
for i, det in enumerate(pred): # per image
seen += 1
if webcam: # batch_size >= 1
p, im0, frame = path[i], im0s[i].copy(), dataset.count
s += f'{i}: '
else:
p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
p = Path(p) # to Path
save_path = str(save_dir / p.name) # im.jpg
txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt
s += '%gx%g ' % im.shape[2:] # print string
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
imc = im0.copy() if save_crop else im0 # for save_crop
annotator = Annotator(im0, line_width=line_thickness, example=str(names))
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
s += f",{n}, {names[int(c)]}{'s' * (n > 1)} " # add to String
print(det[:, -1].unique())
print("c=", c, int(c), names[int(c)] ,{names[int(c)]})
print("n=", n, {n})
print("s=", s, 's', {'s' * (n > 1)})
# 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)
# 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:
if dataset.mode == 'image':
cv2.imwrite(save_path, im0)
else: # 'video' or 'stream'
if vid_path[i] != save_path: # new video
vid_path[i] = save_path
if isinstance(vid_writer[i], cv2.VideoWriter):
vid_writer[i].release() # release previous video writer
if vid_cap: # video
fps = vid_cap.get(cv2.CAP_PROP_FPS)
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
else: # stream
fps, w, h = 30, im0.shape[1], im0.shape[0]
save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos
vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
vid_writer[i].write(im0)
## Print time (inference-only)
t1datetime = datetime.datetime.fromtimestamp(t1)
outputinfo = f'{t1datetime}, {t3 - t2:.3f}s, {s}'
LOGGER.info(outputinfo)
## File output
with open(save_dir / 'output.csv','a') as f:
print(outputinfo,file = f)logger