0

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
5
  • detect.pyをどういうオプションで実行したのかコマンドを載せてください。
    – nandeyanen
    2022年5月5日 13:54
  • 1
    できれば、再現可能な情報をもっと書いていただけると助かります。試したコマンドやコードを載せていただければ回答しやすいです。
    – nandeyanen
    2022年5月5日 14:53
  • やりたいことは、動画上での検出結果をCSVに吐き出すことです。 標準でインストールされるcoco128.yamlで80のclassが学習済みと思います。 python detect.py --source /xxxx.mov --classes 0 1 2 で 3つのclassの結果が出力されると思いますが、検出されないclassは出力さません。 以下のように検出されないclassも0として表示させたいわけです。 class0, class1, class2 1 , 0 , 0 0 , 2 , 0 0 , 2 , 1 0 , 1 , 0 0 , 0 , 0 detect.pyは、print()の部分に、csv出力を追加する程度の追記はしておりますが、それ以外は特に触ってはいません。
    – west1021
    2022年5月6日 4:43
  • print()の部分に追加したcsv出力のコードを質問に追記してくだされば再現できるんじゃないですかね。というのも、デフォルトの状態だとクラス数など表示されず、検出結果を画像として出力するだけになっていると思うので。独自の追加コードを質問文に追記してくだされば回答しやすいですね。
    – nandeyanen
    2022年5月6日 8:04
  • あと試したコマンドやコードはコメントではなくて質問に書いてください。
    – nandeyanen
    2022年5月6日 9:05

0

この質問に回答するには、ログインする必要があります。

のタグが付いた他の質問を参照する。