This commit is contained in:
lichen
2022-04-12 09:43:39 +08:00
parent c1d82fafc4
commit bedb982d73
3 changed files with 72 additions and 71 deletions

137
detect.py
View File

@ -100,44 +100,44 @@ def detect(opt, save_img=False):
n = (det[:, -1] == c).sum() # detections per class n = (det[:, -1] == c).sum() # detections per class
s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
# Write results # # Write results
for *xyxy, conf, cls in reversed(det): # for *xyxy, conf, cls in reversed(det):
if save_txt: # Write to file # if save_txt: # Write to file
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh # xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format # line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format
with open(txt_path + '.txt', 'a') as f: # with open(txt_path + '.txt', 'a') as f:
f.write(('%g ' * len(line)).rstrip() % line + '\n') # f.write(('%g ' * len(line)).rstrip() % line + '\n')
#
if save_img or view_img: # Add bbox to image # if save_img or view_img: # Add bbox to image
label = f'{names[int(cls)]} {conf:.2f}' # label = f'{names[int(cls)]} {conf:.2f}'
plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3) # plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
#
# Print time (inference + NMS) # # Print time (inference + NMS)
print(f'{s}Done. ({t2 - t1:.3f}s)') # print(f'{s}Done. ({t2 - t1:.3f}s)')
#
# Stream results # # Stream results
if view_img: # if view_img:
cv2.imshow(str(p), im0) # cv2.imshow(str(p), im0)
cv2.waitKey(1) # 1 millisecond # cv2.waitKey(1) # 1 millisecond
#
# Save results (image with detections) # # Save results (image with detections)
if save_img: # if save_img:
if dataset.mode == 'image': # if dataset.mode == 'image':
cv2.imwrite(save_path, im0) # cv2.imwrite(save_path, im0)
else: # 'video' or 'stream' # else: # 'video' or 'stream'
if vid_path != save_path: # new video # if vid_path != save_path: # new video
vid_path = save_path # vid_path = save_path
if isinstance(vid_writer, cv2.VideoWriter): # if isinstance(vid_writer, cv2.VideoWriter):
vid_writer.release() # release previous video writer # vid_writer.release() # release previous video writer
if vid_cap: # video # if vid_cap: # video
fps = vid_cap.get(cv2.CAP_PROP_FPS) # fps = vid_cap.get(cv2.CAP_PROP_FPS)
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) # w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) # h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
else: # stream # else: # stream
fps, w, h = 30, im0.shape[1], im0.shape[0] # fps, w, h = 30, im0.shape[1], im0.shape[0]
save_path += '.mp4' # save_path += '.mp4'
vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h)) # vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
vid_writer.write(im0) # vid_writer.write(im0)
if save_txt or save_img: if save_txt or save_img:
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else '' s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
@ -158,33 +158,34 @@ def detect(opt, save_img=False):
if __name__ == '__main__': if __name__ == '__main__':
parser = argparse.ArgumentParser() pass
#parser.add_argument('--weights', nargs='+', type=str, default='runs/zhanting/yolov5s_finetune/exp12/weights/best.pt', help='model.pt path(s)') # parser = argparse.ArgumentParser()
parser.add_argument('--weights', nargs='+', type=str, default='runs/zhanting/yolov5m_finetune/exp4/weights/best.pt', help='model.pt path(s)') # #parser.add_argument('--weights', nargs='+', type=str, default='runs/zhanting/yolov5s_finetune/exp12/weights/best.pt', help='model.pt path(s)')
parser.add_argument('--source', type=str, default='data/pic4', help='source') # file/folder, 0 for webcam # parser.add_argument('--weights', nargs='+', type=str, default='runs/zhanting/yolov5m_finetune/exp4/weights/best.pt', help='model.pt path(s)')
parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)') # parser.add_argument('--source', type=str, default='data/pic4', help='source') # file/folder, 0 for webcam
parser.add_argument('--conf-thres', type=float, default=0.5, help='object confidence threshold') # parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS') # parser.add_argument('--conf-thres', type=float, default=0.5, help='object confidence threshold')
parser.add_argument('--device', default='0,1', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') # parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
parser.add_argument('--view-img', action='store_true', help='display results') # parser.add_argument('--device', default='0,1', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') # parser.add_argument('--view-img', action='store_true', help='display results')
parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels') # parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
parser.add_argument('--nosave', action='store_true', help='do not save images/videos') # parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3') # parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS') # parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
parser.add_argument('--augment', action='store_true', help='augmented inference') # parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
parser.add_argument('--update', action='store_true', help='update all models') # parser.add_argument('--augment', action='store_true', help='augmented inference')
parser.add_argument('--project', default='runs/detect', help='save results to project/name') # parser.add_argument('--update', action='store_true', help='update all models')
parser.add_argument('--name', default='exp', help='save results to project/name') # parser.add_argument('--project', default='runs/detect', help='save results to project/name')
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') # parser.add_argument('--name', default='exp', help='save results to project/name')
opt = parser.parse_args() # parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
print("opt:",opt) # opt = parser.parse_args()
check_requirements(exclude=('pycocotools', 'thop')) # print("opt:",opt)
# check_requirements(exclude=('pycocotools', 'thop'))
with torch.no_grad(): #
if opt.update: # update all models (to fix SourceChangeWarning) # with torch.no_grad():
for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']: # if opt.update: # update all models (to fix SourceChangeWarning)
detect(opt) # for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:
strip_optimizer(opt.weights) # detect(opt)
else: # strip_optimizer(opt.weights)
detect(opt,True) # else:
# detect(opt,True)

View File

@ -69,9 +69,9 @@ def get_isempty():
print('now_time', now_time) print('now_time', now_time)
print('get date use time: {0:.2f}s'.format(getdateend - start)) print('get date use time: {0:.2f}s'.format(getdateend - start))
except: except:
return repr(pred) return pred
return repr(pred) return pred

View File

@ -1,2 +1,2 @@
#!/bin/bash #!/bin/bash
supervisorctl start ieemoo-ai-zhanting supervisorctl stop ieemoo-ai-zhanting