predict_qt.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
  2. """
  3. Run YOLOv5 segmentation inference on images, videos, directories, streams, etc.
  4. Usage - sources:
  5. $ python segment/predict.py --weights yolov5s-seg.pt --source 0 # webcam
  6. img.jpg # image
  7. vid.mp4 # video
  8. screen # screenshot
  9. path/ # directory
  10. list.txt # list of images
  11. list.streams # list of streams
  12. 'path/*.jpg' # glob
  13. 'https://youtu.be/Zgi9g1ksQHc' # YouTube
  14. 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
  15. Usage - formats:
  16. $ python segment/predict.py --weights yolov5s-seg.pt # PyTorch
  17. yolov5s-seg.torchscript # TorchScript
  18. yolov5s-seg.onnx # ONNX Runtime or OpenCV DNN with --dnn
  19. yolov5s-seg_openvino_model # OpenVINO
  20. yolov5s-seg.engine # TensorRT
  21. yolov5s-seg.mlmodel # CoreML (macOS-only)
  22. yolov5s-seg_saved_model # TensorFlow SavedModel
  23. yolov5s-seg.pb # TensorFlow GraphDef
  24. yolov5s-seg.tflite # TensorFlow Lite
  25. yolov5s-seg_edgetpu.tflite # TensorFlow Edge TPU
  26. yolov5s-seg_paddle_model # PaddlePaddle
  27. """
  28. import argparse
  29. import os
  30. import platform
  31. import sys
  32. from pathlib import Path
  33. import torch
  34. FILE = Path(__file__).resolve()
  35. ROOT = FILE.parents[0] # YOLOv5 root directory
  36. if str(ROOT) not in sys.path:
  37. sys.path.append(str(ROOT)) # add ROOT to PATH
  38. ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
  39. from models.common import DetectMultiBackend
  40. from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams, LoadImages_batch
  41. from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
  42. increment_path, non_max_suppression, print_args, scale_boxes, scale_segments,
  43. strip_optimizer)
  44. from utils.plots import Annotator, colors, save_one_box
  45. from utils.segment.general import masks2segments, process_mask, process_mask_native
  46. from utils.segment.dataloaders import polygons2masks
  47. from utils.torch_utils import select_device, smart_inference_mode
  48. import numpy as np
  49. @smart_inference_mode()
  50. def run(
  51. weights=ROOT / 'yolov5s.pt', # model.pt path(s)
  52. source=ROOT / 'data/HRSID_YOLO/val', # file/dir/URL/glob/screen/0(webcam)
  53. data=ROOT / 'data/HRSID_YOLO/dataset.yaml', # dataset.yaml path
  54. imgsz=(640, 640), # inference size (height, width)
  55. conf_thres=0.25, # confidence threshold
  56. iou_thres=0.45, # NMS IOU threshold
  57. max_det=1000, # maximum detections per image
  58. device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
  59. view_img=False, # show results
  60. save_txt=False, # save results to *.txt
  61. save_conf=False, # save confidences in --save-txt labels
  62. save_crop=False, # save cropped prediction boxes
  63. nosave=False, # do not save images/videos
  64. classes=None, # filter by class: --class 0, or --class 0 2 3
  65. agnostic_nms=False, # class-agnostic NMS
  66. augment=False, # augmented inference
  67. visualize=False, # visualize features
  68. update=False, # update all models
  69. project=ROOT / 'runs/predict-seg', # save results to project/name
  70. name='exp', # save results to project/name
  71. exist_ok=False, # existing project/name ok, do not increment
  72. line_thickness=3, # bounding box thickness (pixels)
  73. hide_labels=False, # hide labels
  74. hide_conf=False, # hide confidences
  75. half=False, # use FP16 half-precision inference
  76. dnn=False, # use OpenCV DNN for ONNX inference
  77. vid_stride=1, # video frame-rate stride
  78. retina_masks=False,
  79. batch_size=16,
  80. ):
  81. source = str(source)
  82. save_img = not nosave and not source.endswith('.txt') # save inference images
  83. is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
  84. is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
  85. webcam = source.isnumeric() or source.endswith('.streams') or (is_url and not is_file)
  86. screenshot = source.lower().startswith('screen')
  87. if is_url and is_file:
  88. source = check_file(source) # download
  89. # Directories
  90. save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
  91. (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
  92. (save_dir / 'jsons' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
  93. logFile = save_dir / 'detect.txt'
  94. import logging
  95. LOGGER = logging.getLogger('yolov5')
  96. logging.basicConfig(level=logging.INFO)
  97. # 创建一个FileHandler,并将日志写入指定的日志文件中
  98. fileHandler = logging.FileHandler(logFile, mode='a', encoding="utf-8")
  99. fileHandler.setLevel(logging.INFO)
  100. # 定义Handler的日志输出格式
  101. # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  102. formatter = logging.Formatter('%(asctime)s - %(message)s')
  103. fileHandler.setFormatter(formatter)
  104. # 添加Handler
  105. LOGGER.addHandler(fileHandler)
  106. # Load model
  107. device = select_device(device)
  108. model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
  109. stride, names, pt = model.stride, model.names, model.pt
  110. nmm = len(list(names.keys()))
  111. imgsz = check_img_size(imgsz, s=stride) # check image size
  112. # Dataloader
  113. bs = batch_size # batch_size
  114. if webcam:
  115. view_img = check_imshow(warn=True)
  116. dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
  117. bs = len(dataset)
  118. elif screenshot:
  119. dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
  120. else:
  121. if bs == 1:
  122. dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
  123. else:
  124. from torch.utils.data import DataLoader
  125. dataset = LoadImages_batch(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
  126. bs = min(bs, len(dataset))
  127. dataloader = DataLoader(dataset,
  128. batch_size=bs,
  129. shuffle=True,
  130. num_workers=4,
  131. pin_memory=True,
  132. collate_fn=LoadImages_batch.collate_fn)
  133. vid_path, vid_writer = [None] * bs, [None] * bs
  134. # Run inference
  135. model.warmup(imgsz=(1 if pt else bs, 3, *imgsz)) # warmup
  136. seen, windows, dt = 0, [], (Profile(), Profile(), Profile())
  137. if bs == 1:
  138. for path, im, im0s, vid_cap, s in dataset:
  139. with dt[0]:
  140. im = torch.from_numpy(im).to(model.device)
  141. im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
  142. im /= 255 # 0 - 255 to 0.0 - 1.0
  143. if len(im.shape) == 3:
  144. im = im[None] # expand for batch dim
  145. # Inference
  146. with dt[1]:
  147. visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
  148. pred, proto = model(im, augment=augment, visualize=visualize)[:2]
  149. # NMS
  150. with dt[2]:
  151. # if pred.numel() > 0: # numel() 返回张量中元素的数量
  152. # pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms,
  153. # max_det=max_det, nm=nm)
  154. # else:
  155. # print("No valid predictions, skipping non_max_suppression.")
  156. # pred = torch.empty((0, 6)) # 返回一个空的张量以避免后续错误
  157. # print(pred)
  158. pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det, nm=nmm)
  159. # Second-stage classifier (optional)
  160. # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
  161. # Process predictions
  162. for i, det in enumerate(pred): # per image
  163. seen += 1
  164. if webcam: # batch_size >= 1
  165. p, im0, frame = path[i], im0s[i].copy(), dataset.count
  166. s += f'{i}: '
  167. else:
  168. p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
  169. p = Path(p) # to Path
  170. save_path = str(save_dir / p.name) # im.jpg
  171. txt_path = str(save_dir / 'labels' / p.stem) + (
  172. '' if dataset.mode == 'image' else f'_{frame}') # im.txt
  173. labelme_path = str(save_dir / 'jsons' / p.stem) + (
  174. '' if dataset.mode == 'image' else f'_{frame}') # im.json
  175. label_dict = {}
  176. label_dict['version'] = '5.0.1'
  177. label_dict['flags'] = {}
  178. label_dict['imageData'] = None
  179. label_dict['imagePath'] = p.name
  180. label_dict['imageHeight'] = im0.shape[0]
  181. label_dict['imageWidth'] = im0.shape[1]
  182. label_dict['shapes'] = []
  183. s += '%gx%g ' % im.shape[2:] # print string
  184. imc = im0.copy() if save_crop else im0 # for save_crop
  185. annotator = Annotator(im0, line_width=line_thickness, example=str(names))
  186. if len(det):
  187. if retina_masks:
  188. # scale bbox first the crop masks
  189. det[:, :4] = scale_boxes(im.shape[2:], det[:, :4],
  190. im0.shape).round() # rescale boxes to im0 size
  191. masks = process_mask_native(proto[i], det[:, 6:], det[:, :4], im0.shape[:2]) # HWC
  192. else:
  193. masks = process_mask(proto[i], det[:, 6:], det[:, :4], im.shape[2:], upsample=True) # HWC
  194. det[:, :4] = scale_boxes(im.shape[2:], det[:, :4],
  195. im0.shape).round() # rescale boxes to im0 size
  196. # Segments
  197. if save_txt:
  198. segments = [
  199. scale_segments(im0.shape if retina_masks else im.shape[2:], x, im0.shape, normalize=False)
  200. for x in reversed(masks2segments(masks))] # ,strategy='concat'
  201. # Print results
  202. for c in det[:, 5].unique():
  203. n = (det[:, 5] == c).sum() # detections per class
  204. s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
  205. # Mask plotting
  206. annotator.masks(
  207. masks,
  208. colors=[colors(x, True) for x in det[:, 5]],
  209. im_gpu=torch.as_tensor(im0, dtype=torch.float16).to(device).permute(2, 0, 1).flip(
  210. 0).contiguous() /
  211. 255 if retina_masks else im[i])
  212. # Write results
  213. for j, (*xyxy, conf, cls) in enumerate(reversed(det[:, :6])):
  214. if save_txt: # Write to file
  215. seg = segments[j].reshape(-1) # (n,2) to (n*2)
  216. line = (cls, *seg, conf) if save_conf else (cls, *seg) # label format
  217. with open(f'{txt_path}.txt', 'a') as f:
  218. f.write(('%g ' * len(line)).rstrip() % line + '\n')
  219. # add save_labeme format
  220. tmp = {}
  221. tmp['label'] = names[int(cls)]
  222. # tmp['label_id'] = int(cls)
  223. tmp['points'] = segments[
  224. j].tolist() # [[float(xyxy[0].detach().item()), float(xyxy[1].detach().item())], [float(xyxy[2].detach().item()), float(xyxy[3].detach().item())]]
  225. tmp['group_id'] = None
  226. tmp['shape_type'] = 'polygon' # 注意修改
  227. tmp['flags'] = {}
  228. # tmp['bbox'] = [xyxy[0].tolist(),xyxy[1].tolist()]
  229. label_dict['shapes'].append(tmp)
  230. if save_img or save_crop or view_img: # Add bbox to image
  231. c = int(cls) # integer class
  232. label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
  233. annotator.box_label(xyxy, label, color=colors(c, True), flag=False)
  234. # # annotator.draw.polygon(segments[j], outline=colors(c, True), width=3)
  235. if save_crop:
  236. save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
  237. if save_txt: # Write to file
  238. import json
  239. with open(f'{labelme_path}.json', 'w') as f:
  240. json.dump(label_dict, f)
  241. # Stream results
  242. im0 = annotator.result()
  243. if view_img:
  244. if platform.system() == 'Linux' and p not in windows:
  245. windows.append(p)
  246. cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
  247. cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
  248. cv2.imshow(str(p), im0)
  249. if cv2.waitKey(1) == ord('q'): # 1 millisecond
  250. exit()
  251. # Save results (image with detections)
  252. if save_img:
  253. if dataset.mode == 'image':
  254. cv2.imwrite(save_path, im0)
  255. else: # 'video' or 'stream'
  256. if vid_path[i] != save_path: # new video
  257. vid_path[i] = save_path
  258. if isinstance(vid_writer[i], cv2.VideoWriter):
  259. vid_writer[i].release() # release previous video writer
  260. if vid_cap: # video
  261. fps = vid_cap.get(cv2.CAP_PROP_FPS)
  262. w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  263. h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  264. else: # stream
  265. fps, w, h = 30, im0.shape[1], im0.shape[0]
  266. save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos
  267. vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
  268. vid_writer[i].write(im0)
  269. # Print time (inference-only)
  270. LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms")
  271. f_for_val = open('x.excel', 'w')
  272. f_for_val.writelines(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms")
  273. else:
  274. for batch_i, (paths, im, im0s, s) in enumerate(dataloader):
  275. with dt[0]:
  276. im = im.to(device, non_blocking=True)
  277. im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
  278. im /= 255 # 0 - 255 to 0.0 - 1.0
  279. # Inference
  280. with dt[1]:
  281. # visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
  282. pred, proto = model(im, augment=augment, visualize=False)[:2]
  283. # NMS
  284. with dt[2]:
  285. if pred.numel() > 0: # numel() 返回张量中元素的数量
  286. pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms,
  287. max_det=max_det, nm=nm)
  288. else:
  289. print("No valid predictions, skipping non_max_suppression.")
  290. pred = torch.empty((0, 6)) # 返回一个空的张量以避免后续错误
  291. pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det, nm=nmm)
  292. # Second-stage classifier (optional)
  293. # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
  294. # Process predictions
  295. for i, det in enumerate(pred): # per image
  296. seen += 1
  297. if webcam: # batch_size >= 1
  298. p, im0, frame = paths[i], im0s[i].copy(), dataset.count
  299. s += f'{i}: '
  300. else:
  301. p, im0, frame = paths[i], im0s[i].numpy().copy(), getattr(dataset, 'frame', 0)
  302. s[i] += f'{i}: '
  303. p = Path(p) # to Path
  304. save_path = str(save_dir / p.name) # im.jpg
  305. txt_path = str(save_dir / 'labels' / p.stem) + (
  306. '' if dataset.mode == 'image' else f'_{frame}') # im.txt
  307. labelme_path = str(save_dir / 'jsons' / p.stem) + (
  308. '' if dataset.mode == 'image' else f'_{frame}') # im.json
  309. label_dict = {}
  310. label_dict['version'] = '5.0.1'
  311. label_dict['flags'] = {}
  312. label_dict['imageData'] = None
  313. label_dict['imagePath'] = p.name
  314. label_dict['imageHeight'] = im0.shape[0]
  315. label_dict['imageWidth'] = im0.shape[1]
  316. label_dict['shapes'] = []
  317. s += '%gx%g ' % im.shape[2:] # print string
  318. imc = im0.copy() if save_crop else im0 # for save_crop
  319. annotator = Annotator(im0, line_width=line_thickness, example=str(names))
  320. if len(det):
  321. if retina_masks:
  322. # scale bbox first the crop masks
  323. det[:, :4] = scale_boxes(im.shape[2:], det[:, :4],
  324. im0.shape).round() # rescale boxes to im0 size
  325. masks = process_mask_native(proto[i], det[:, 6:], det[:, :4], im0.shape[:2]) # HWC
  326. else:
  327. masks = process_mask(proto[i], det[:, 6:], det[:, :4], im.shape[2:], upsample=True) # HWC
  328. det[:, :4] = scale_boxes(im.shape[2:], det[:, :4],
  329. im0.shape).round() # rescale boxes to im0 size
  330. # Segments
  331. if save_txt:
  332. segments = [
  333. scale_segments(im0.shape if retina_masks else im.shape[2:], x, im0.shape, normalize=False)
  334. for x in reversed(masks2segments(masks))]
  335. # Print results
  336. for c in det[:, 5].unique():
  337. n = (det[:, 5] == c).sum() # detections per class
  338. s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
  339. # Mask plotting
  340. annotator.masks(
  341. masks,
  342. colors=[colors(x, True) for x in det[:, 5]],
  343. im_gpu=torch.as_tensor(im0, dtype=torch.float16).to(device).permute(2, 0, 1).flip(
  344. 0).contiguous() /
  345. 255 if retina_masks else im[i])
  346. # Write results
  347. for j, (*xyxy, conf, cls) in enumerate(reversed(det[:, :6])):
  348. if save_txt: # Write to file
  349. seg = segments[j].reshape(-1) # (n,2) to (n*2)
  350. line = (cls, *seg, conf) if save_conf else (cls, *seg) # label format
  351. with open(f'{txt_path}.txt', 'a') as f:
  352. f.write(('%g ' * len(line)).rstrip() % line + '\n')
  353. # add save_labeme format
  354. tmp = {}
  355. tmp['label'] = names[int(cls)]
  356. tmp['points'] = segments[
  357. j].tolist() # E[float(xyxy[0].detach().item()), float(xyxy[1].detach().item())], [float(xyxy[2].detach().item()), float(xyxy[3].detach().item())]
  358. tmp['group_id'] = None
  359. tmp['shape_type'] = 'polygon' # 注意修改
  360. # area = component_polygon_area(segments[j])
  361. # tmp['area'] = area
  362. # tmp['lenth'] = component_polygon_Circle(segments[j])# 宽度
  363. # tmp['width'] = component_polygon_Circle(segments[j])
  364. tmp['flags'] = {}
  365. label_dict['shapes'].append(tmp)
  366. if save_img or save_crop or view_img: # Add bbox to image
  367. c = int(cls) # integer class
  368. label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
  369. annotator.box_label(xyxy, label, color=colors(c, True), flag=False)
  370. # annotator.draw.polygon(segments[j], outline=colors(c, True), width=3)
  371. if save_crop:
  372. save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
  373. if save_txt: # Write to file
  374. import json
  375. with open(f'{labelme_path}.json', 'w') as f:
  376. json.dump(label_dict, f)
  377. # # copy file
  378. # import shutil
  379. # #shutil.copyfile(f'{labelme_path}.json', os.path.dirname(source) + f'{labelme_path}.json')
  380. # if os.path.isdir(source):
  381. # shutil.copyfile(f'{labelme_path}.json',os.path.join(source,f'{p.stem}.json'))
  382. # else:
  383. # shutil.copyfile(f'{labelme_path}.json',os.path.join(os.path.dirname(source),f'{p.stem}.json'))
  384. else:
  385. # 不存在 检测结果
  386. if save_txt: # Write to file
  387. # add save_labeme format
  388. tmp = {}
  389. tmp['label'] = "" # names[int(cls)]
  390. tmp['points'] = [
  391. []] # segments[j].tolist() #E[float(xyxy[0].detach().item()), float(xyxy[1].detach().item())], [float(xyxy[2].detach().item()), float(xyxy[3].detach().item())]
  392. tmp['group_id'] = None
  393. tmp['shape_type'] = 'polygon' # 注意修改
  394. # area = component_polygon_area(segments[j])
  395. # tmp['area'] = area
  396. # tmp['lenth'] = component_polygon_Circle(segments[j])# 宽度
  397. # tmp['width'] = component_polygon_Circle(segments[j])
  398. tmp['flags'] = {}
  399. label_dict['shapes'].append(tmp)
  400. import json
  401. with open(f'{labelme_path}.json', 'w') as f:
  402. json.dump(label_dict, f)
  403. # Stream results
  404. im0 = annotator.result()
  405. if view_img:
  406. if platform.system() == 'Linux' and p not in windows:
  407. windows.append(p)
  408. cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
  409. cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
  410. cv2.imshow(str(p), im0)
  411. if cv2.waitKey(1) == ord('q'): # 1 millisecond
  412. exit()
  413. # Save results (image with detections)
  414. if save_img:
  415. if dataset.mode == 'image':
  416. cv2.imwrite(save_path, im0)
  417. else: # 'video' or 'stream'
  418. if vid_path[i] != save_path: # new video
  419. vid_path[i] = save_path
  420. if isinstance(vid_writer[i], cv2.VideoWriter):
  421. vid_writer[i].release() # release previous video writer
  422. if vid_cap: # video
  423. fps = vid_cap.get(cv2.CAP_PROP_FPS)
  424. w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  425. h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  426. else: # stream
  427. fps, w, h = 30, im0.shape[1], im0.shape[0]
  428. save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos
  429. vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
  430. vid_writer[i].write(im0)
  431. # Print time (inference-only)
  432. LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms")
  433. f_for_val.writelines(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms")
  434. f_for_val.close()
  435. # Print results
  436. t = tuple(x.t / seen * 1E3 for x in dt) # speeds per image
  437. LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
  438. if save_txt or save_img:
  439. s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
  440. LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
  441. if update:
  442. strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
  443. def parse_opt():
  444. parser = argparse.ArgumentParser()
  445. parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'weights\\best.pt', help='model path(s)')
  446. parser.add_argument('--source', type=str, default=ROOT / 'data\\HRSID_YOLO\\test\\images', help='file/dir/URL/glob/screen/0(webcam)')
  447. parser.add_argument('--data', type=str, default=ROOT / 'data\HRSID_YOLO\dataset.yaml', help='(optional) dataset.yaml path')
  448. parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
  449. parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
  450. parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
  451. parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
  452. parser.add_argument('--device', default='0', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  453. parser.add_argument('--view-img', action='store_true', help='show results')
  454. parser.add_argument('--save-txt', action='store_true', default=True, help='save results to *.txt')
  455. parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
  456. parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
  457. parser.add_argument('--nosave', action='store_true', default=True, help='do not save images/videos')
  458. parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
  459. parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
  460. parser.add_argument('--augment', action='store_true', help='augmented inference')
  461. parser.add_argument('--visualize', action='store_true', help='visualize features')
  462. parser.add_argument('--update', action='store_true', help='update all models')
  463. parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')
  464. parser.add_argument('--name', default='exp', help='save results to project/name')
  465. parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
  466. parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
  467. parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
  468. parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
  469. parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
  470. parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
  471. parser.add_argument('--vid-stride', type=int, default=1, help='video frame-rate stride')
  472. parser.add_argument('--retina-masks', action='store_true', help='whether to plot masks in native resolution')
  473. parser.add_argument('--batch-size', type=int, default=1, help='total batch size for all GPUs, -1 for autobatch')
  474. opt = parser.parse_args()
  475. opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
  476. print_args(vars(opt))
  477. return opt
  478. def main(opt):
  479. check_requirements(exclude=('tensorboard', 'thop'))
  480. run(**vars(opt))
  481. if __name__ == "__main__":
  482. opt = parse_opt()
  483. main(opt)