質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
YOLO

YOLOとは、画像検出および認識用ニューラルネットワークです。CベースのDarknetというフレームワークを用いて、画像や動画からオブジェクトを検出。リアルタイムでそれが何になるのかを認識し、分類することができます。

OpenCV

OpenCV(オープンソースコンピュータービジョン)は、1999年にインテルが開発・公開したオープンソースのコンピュータビジョン向けのクロスプラットフォームライブラリです。

機械学習

機械学習は、データからパターンを自動的に発見し、そこから知能的な判断を下すためのコンピューターアルゴリズムを指します。人工知能における課題のひとつです。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

0回答

2609閲覧

PythonでYOLOv5のresultを取得したい

Pino02

総合スコア1

YOLO

YOLOとは、画像検出および認識用ニューラルネットワークです。CベースのDarknetというフレームワークを用いて、画像や動画からオブジェクトを検出。リアルタイムでそれが何になるのかを認識し、分類することができます。

OpenCV

OpenCV(オープンソースコンピュータービジョン)は、1999年にインテルが開発・公開したオープンソースのコンピュータビジョン向けのクロスプラットフォームライブラリです。

機械学習

機械学習は、データからパターンを自動的に発見し、そこから知能的な判断を下すためのコンピューターアルゴリズムを指します。人工知能における課題のひとつです。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2021/03/12 18:38

編集2021/03/13 05:45

#PythonでYOLOv5のresultを取得したい

前提・実現したいこと

コンソール上にしか結果が表示されないのでそれをtxtファイルに出力したいです。

発生している問題・エラーメッセージ

yolov5-masterというディレクトリにYOLOv5のファイルを解凍してあります。
その中のdetect.pyをpython detect.py --source 0で実行しました。
そうするとコマンドプロントには下記のものはその一部ですが結果が返ってきます。
ですがこれをtxtファイルに出力できなくて困っています。

試したこと

とりあえずprintしているところが118行目の

python

1print(f'{s}Done. ({t2 - t1:.3f}s)')

だと分かったのでこれを変数に格納して
強引に結果を切り取ったりしてみました。

python

1result = f'{s}Done. ({t2 - t1:.3f}s)' 2result = result[14:]

Code

Python

1detect.py 2 3import argparse 4import time 5from pathlib import Path 6 7import cv2 8import torch 9import torch.backends.cudnn as cudnn 10from numpy import random 11 12from models.experimental import attempt_load 13from utils.datasets import LoadStreams, LoadImages 14from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \ 15 scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path 16from utils.plots import plot_one_box 17from utils.torch_utils import select_device, load_classifier, time_synchronized 18 19 20def detect(save_img=False): 21 source, weights, view_img, save_txt, imgsz = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size 22 webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith( 23 ('rtsp://', 'rtmp://', 'http://')) 24 25 # Directories 26 save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)) # increment run 27 (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir 28 29 # Initialize 30 set_logging() 31 device = select_device(opt.device) 32 half = device.type != 'cpu' # half precision only supported on CUDA 33 34 # Load model 35 model = attempt_load(weights, map_location=device) # load FP32 model 36 stride = int(model.stride.max()) # model stride 37 imgsz = check_img_size(imgsz, s=stride) # check img_size 38 if half: 39 model.half() # to FP16 40 41 # Second-stage classifier 42 classify = False 43 if classify: 44 modelc = load_classifier(name='resnet101', n=2) # initialize 45 modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval() 46 47 # Set Dataloader 48 vid_path, vid_writer = None, None 49 if webcam: 50 view_img = check_imshow() 51 cudnn.benchmark = True # set True to speed up constant image size inference 52 dataset = LoadStreams(source, img_size=imgsz, stride=stride) 53 else: 54 save_img = True 55 dataset = LoadImages(source, img_size=imgsz, stride=stride) 56 57 # Get names and colors 58 names = model.module.names if hasattr(model, 'module') else model.names 59 colors = [[random.randint(0, 255) for _ in range(3)] for _ in names] 60 61 # Run inference 62 if device.type != 'cpu': 63 model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once 64 t0 = time.time() 65 for path, img, im0s, vid_cap in dataset: 66 img = torch.from_numpy(img).to(device) 67 img = img.half() if half else img.float() # uint8 to fp16/32 68 img /= 255.0 # 0 - 255 to 0.0 - 1.0 69 if img.ndimension() == 3: 70 img = img.unsqueeze(0) 71 72 # Inference 73 t1 = time_synchronized() 74 pred = model(img, augment=opt.augment)[0] 75 76 # Apply NMS 77 pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms) 78 t2 = time_synchronized() 79 80 # Apply Classifier 81 if classify: 82 pred = apply_classifier(pred, modelc, img, im0s) 83 84 # Process detections 85 for i, det in enumerate(pred): # detections per image 86 if webcam: # batch_size >= 1 87 p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count 88 else: 89 p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0) 90 91 p = Path(p) # to Path 92 save_path = str(save_dir / p.name) # img.jpg 93 txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt 94 s += '%gx%g ' % img.shape[2:] # print string 95 gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh 96 if len(det): 97 # Rescale boxes from img_size to im0 size 98 det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round() 99 100 # Print results 101 for c in det[:, -1].unique(): 102 n = (det[:, -1] == c).sum() # detections per class 103 s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string 104 105 # Write results 106 for *xyxy, conf, cls in reversed(det): 107 if save_txt: # Write to file 108 xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh 109 line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format 110 with open(txt_path + '.txt', 'a') as f: 111 f.write(('%g ' * len(line)).rstrip() % line + '\n') 112 113 if save_img or view_img: # Add bbox to image 114 label = f'{names[int(cls)]} {conf:.2f}' 115 plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3) 116 117 # Print time (inference + NMS) 118 print(f'{s}Done. ({t2 - t1:.3f}s)') 119 120 # Stream results 121 if view_img: 122 cv2.imshow(str(p), im0) 123 cv2.waitKey(1) # 1 millisecond 124 125 # Save results (image with detections) 126 if save_img: 127 if dataset.mode == 'image': 128 cv2.imwrite(save_path, im0) 129 else: # 'video' 130 if vid_path != save_path: # new video 131 vid_path = save_path 132 if isinstance(vid_writer, cv2.VideoWriter): 133 vid_writer.release() # release previous video writer 134 135 fourcc = 'mp4v' # output video codec 136 fps = vid_cap.get(cv2.CAP_PROP_FPS) 137 w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) 138 h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) 139 vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*fourcc), fps, (w, h)) 140 vid_writer.write(im0) 141 142 if save_txt or save_img: 143 s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else '' 144 print(f"Results saved to {save_dir}{s}") 145 146 print(f'Done. ({time.time() - t0:.3f}s)') 147 148 149if __name__ == '__main__': 150 parser = argparse.ArgumentParser() 151 parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)') 152 parser.add_argument('--source', type=str, default='data/images', help='source') # file/folder, 0 for webcam 153 parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)') 154 parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold') 155 parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS') 156 parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 157 parser.add_argument('--view-img', action='store_true', help='display results') 158 parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') 159 parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels') 160 parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3') 161 parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS') 162 parser.add_argument('--augment', action='store_true', help='augmented inference') 163 parser.add_argument('--update', action='store_true', help='update all models') 164 parser.add_argument('--project', default='runs/detect', help='save results to project/name') 165 parser.add_argument('--name', default='exp', help='save results to project/name') 166 parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') 167 opt = parser.parse_args() 168 print(opt) 169 check_requirements() 170 171 with torch.no_grad(): 172 if opt.update: # update all models (to fix SourceChangeWarning) 173 for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']: 174 detect() 175 strip_optimizer(opt.weights) 176 else: 177 detect()

cmd

10: 480x640 1 tv, Done. (0.219s) 20: 480x640 1 tv, 1 book, Done. (0.224s) 30: 480x640 1 person, Done. (0.215s) 40: 480x640 Done. (0.217s) 50: 480x640 Done. (0.212s) 60: 480x640 1 tv, Done. (0.205s) 70: 480x640 1 tie, Done. (0.208s) 80: 480x640 Done. (0.211s) 90: 480x640 1 person, Done. (0.219s) 100: 480x640 Done. (0.204s) 110: 480x640 1 chair, Done. (0.218s) 120: 480x640 1 carrot, Done. (0.210s) 130: 480x640 Done. (0.212s) 140: 480x640 Done. (0.215s) 150: 480x640 1 person, Done. (0.211s) 160: 480x640 1 person, Done. (0.214s) 170: 480x640 1 person, 1 tv, 1 laptop, Done. (0.208s)

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問