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