teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

1

丸投げな質問だったため詳細を追記しました!ご迷惑おかけします。。

2021/03/13 05:45

投稿

Pino02
Pino02

スコア1

title CHANGED
File without changes
body CHANGED
@@ -1,3 +1,222 @@
1
1
  #PythonでYOLOv5のresultを取得したい
2
2
 
3
+ ### 前提・実現したいこと
3
- YOLOv5を使ってWebCamでリアルタイムで認識はしてくれいるんですが、コンソール上にしか結果が表示されないのでそれをtxtファイルに出力したいです。
4
+ コンソール上にしか結果が表示されないのでそれをtxtファイルに出力したいです。
5
+
6
+ ### 発生している問題・エラーメッセージ
7
+ yolov5-masterというディレクトリにYOLOv5のファイルを解凍してあります。
8
+ その中のdetect.pyを`python detect.py --source 0`で実行しました。
9
+ そうするとコマンドプロントには下記のものはその一部ですが結果が返ってきます。
10
+ ですがこれをtxtファイルに出力できなくて困っています。
11
+
12
+ ### 試したこと
13
+ とりあえずprintしているところが118行目の
14
+ ```python
15
+ print(f'{s}Done. ({t2 - t1:.3f}s)')
16
+ ```
17
+ だと分かったのでこれを変数に格納して
18
+ 強引に結果を切り取ったりしてみました。
19
+ ```python
20
+ result = f'{s}Done. ({t2 - t1:.3f}s)'
21
+ result = result[14:]
22
+ ```
23
+ ### Code
24
+ ```Python
25
+ detect.py
26
+
27
+ import argparse
28
+ import time
29
+ from pathlib import Path
30
+
31
+ import cv2
32
+ import torch
33
+ import torch.backends.cudnn as cudnn
34
+ from numpy import random
35
+
36
+ from models.experimental import attempt_load
37
+ from utils.datasets import LoadStreams, LoadImages
38
+ from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \
39
+ scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path
40
+ from utils.plots import plot_one_box
41
+ from utils.torch_utils import select_device, load_classifier, time_synchronized
42
+
43
+
44
+ def detect(save_img=False):
45
+ source, weights, view_img, save_txt, imgsz = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size
46
+ webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
47
+ ('rtsp://', 'rtmp://', 'http://'))
48
+
49
+ # Directories
50
+ save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)) # increment run
51
+ (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
52
+
53
+ # Initialize
54
+ set_logging()
55
+ device = select_device(opt.device)
56
+ half = device.type != 'cpu' # half precision only supported on CUDA
57
+
58
+ # Load model
59
+ model = attempt_load(weights, map_location=device) # load FP32 model
60
+ stride = int(model.stride.max()) # model stride
61
+ imgsz = check_img_size(imgsz, s=stride) # check img_size
62
+ if half:
63
+ model.half() # to FP16
64
+
65
+ # Second-stage classifier
66
+ classify = False
67
+ if classify:
68
+ modelc = load_classifier(name='resnet101', n=2) # initialize
69
+ modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()
70
+
71
+ # Set Dataloader
72
+ vid_path, vid_writer = None, None
73
+ if webcam:
74
+ view_img = check_imshow()
75
+ cudnn.benchmark = True # set True to speed up constant image size inference
76
+ dataset = LoadStreams(source, img_size=imgsz, stride=stride)
77
+ else:
78
+ save_img = True
79
+ dataset = LoadImages(source, img_size=imgsz, stride=stride)
80
+
81
+ # Get names and colors
82
+ names = model.module.names if hasattr(model, 'module') else model.names
83
+ colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]
84
+
85
+ # Run inference
86
+ if device.type != 'cpu':
87
+ model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
88
+ t0 = time.time()
89
+ for path, img, im0s, vid_cap in dataset:
90
+ img = torch.from_numpy(img).to(device)
91
+ img = img.half() if half else img.float() # uint8 to fp16/32
92
+ img /= 255.0 # 0 - 255 to 0.0 - 1.0
93
+ if img.ndimension() == 3:
94
+ img = img.unsqueeze(0)
95
+
96
+ # Inference
97
+ t1 = time_synchronized()
98
+ pred = model(img, augment=opt.augment)[0]
99
+
100
+ # Apply NMS
101
+ pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
102
+ t2 = time_synchronized()
103
+
104
+ # Apply Classifier
105
+ if classify:
106
+ pred = apply_classifier(pred, modelc, img, im0s)
107
+
108
+ # Process detections
109
+ for i, det in enumerate(pred): # detections per image
110
+ if webcam: # batch_size >= 1
111
+ p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
112
+ else:
113
+ p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)
114
+
115
+ p = Path(p) # to Path
116
+ save_path = str(save_dir / p.name) # img.jpg
117
+ txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
118
+ s += '%gx%g ' % img.shape[2:] # print string
119
+ gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
120
+ if len(det):
121
+ # Rescale boxes from img_size to im0 size
122
+ det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
123
+
124
+ # Print results
125
+ for c in det[:, -1].unique():
126
+ n = (det[:, -1] == c).sum() # detections per class
127
+ s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
128
+
129
+ # Write results
130
+ for *xyxy, conf, cls in reversed(det):
131
+ if save_txt: # Write to file
132
+ xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
133
+ line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format
134
+ with open(txt_path + '.txt', 'a') as f:
135
+ f.write(('%g ' * len(line)).rstrip() % line + '\n')
136
+
137
+ if save_img or view_img: # Add bbox to image
138
+ label = f'{names[int(cls)]} {conf:.2f}'
139
+ plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
140
+
141
+ # Print time (inference + NMS)
142
+ print(f'{s}Done. ({t2 - t1:.3f}s)')
143
+
144
+ # Stream results
145
+ if view_img:
146
+ cv2.imshow(str(p), im0)
147
+ cv2.waitKey(1) # 1 millisecond
148
+
149
+ # Save results (image with detections)
150
+ if save_img:
151
+ if dataset.mode == 'image':
152
+ cv2.imwrite(save_path, im0)
153
+ else: # 'video'
154
+ if vid_path != save_path: # new video
155
+ vid_path = save_path
156
+ if isinstance(vid_writer, cv2.VideoWriter):
157
+ vid_writer.release() # release previous video writer
158
+
159
+ fourcc = 'mp4v' # output video codec
160
+ fps = vid_cap.get(cv2.CAP_PROP_FPS)
161
+ w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
162
+ h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
163
+ vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*fourcc), fps, (w, h))
164
+ vid_writer.write(im0)
165
+
166
+ if save_txt or save_img:
167
+ s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
168
+ print(f"Results saved to {save_dir}{s}")
169
+
170
+ print(f'Done. ({time.time() - t0:.3f}s)')
171
+
172
+
173
+ if __name__ == '__main__':
174
+ parser = argparse.ArgumentParser()
175
+ parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)')
176
+ parser.add_argument('--source', type=str, default='data/images', help='source') # file/folder, 0 for webcam
177
+ parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
178
+ parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
179
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
180
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
181
+ parser.add_argument('--view-img', action='store_true', help='display results')
182
+ parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
183
+ parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
184
+ parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
185
+ parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
186
+ parser.add_argument('--augment', action='store_true', help='augmented inference')
187
+ parser.add_argument('--update', action='store_true', help='update all models')
188
+ parser.add_argument('--project', default='runs/detect', help='save results to project/name')
189
+ parser.add_argument('--name', default='exp', help='save results to project/name')
190
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
191
+ opt = parser.parse_args()
192
+ print(opt)
193
+ check_requirements()
194
+
195
+ with torch.no_grad():
196
+ if opt.update: # update all models (to fix SourceChangeWarning)
197
+ for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:
198
+ detect()
199
+ strip_optimizer(opt.weights)
200
+ else:
201
+ detect()
202
+ ```
203
+
204
+ ```cmd
205
+ 0: 480x640 1 tv, Done. (0.219s)
206
+ 0: 480x640 1 tv, 1 book, Done. (0.224s)
207
+ 0: 480x640 1 person, Done. (0.215s)
208
+ 0: 480x640 Done. (0.217s)
209
+ 0: 480x640 Done. (0.212s)
210
+ 0: 480x640 1 tv, Done. (0.205s)
211
+ 0: 480x640 1 tie, Done. (0.208s)
212
+ 0: 480x640 Done. (0.211s)
213
+ 0: 480x640 1 person, Done. (0.219s)
214
+ 0: 480x640 Done. (0.204s)
215
+ 0: 480x640 1 chair, Done. (0.218s)
216
+ 0: 480x640 1 carrot, Done. (0.210s)
217
+ 0: 480x640 Done. (0.212s)
218
+ 0: 480x640 Done. (0.215s)
219
+ 0: 480x640 1 person, Done. (0.211s)
220
+ 0: 480x640 1 person, Done. (0.214s)
221
+ 0: 480x640 1 person, 1 tv, 1 laptop, Done. (0.208s)
222
+ ```