Files changed (4) hide show
  1. .gitattributes +2 -0
  2. app.py +161 -180
  3. input_0.mp4 +3 -0
  4. input_1.mp4 +3 -0
.gitattributes CHANGED
@@ -25,3 +25,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
25
  *.zip filter=lfs diff=lfs merge=lfs -text
26
  *.zstandard filter=lfs diff=lfs merge=lfs -text
27
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
25
  *.zip filter=lfs diff=lfs merge=lfs -text
26
  *.zstandard filter=lfs diff=lfs merge=lfs -text
27
  *tfevents* filter=lfs diff=lfs merge=lfs -text
28
+ input_0.mp4 filter=lfs diff=lfs merge=lfs -text
29
+ input_1.mp4 filter=lfs diff=lfs merge=lfs -text
app.py CHANGED
@@ -1,197 +1,178 @@
 
1
  import gradio as gr
2
- import os
3
-
4
- import argparse
5
- import time
6
- from pathlib import Path
7
-
8
  import cv2
9
- import torch
10
- import torch.backends.cudnn as cudnn
11
- from numpy import random
12
-
13
  from models.experimental import attempt_load
14
- from utils.datasets import LoadStreams, LoadImages
15
- from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \
16
- scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path
17
  from utils.plots import plot_one_box
18
- from utils.torch_utils import select_device, load_classifier, time_synchronized, TracedModel
19
- from PIL import Image
20
-
21
  from huggingface_hub import hf_hub_download
22
 
23
 
24
- def load_model(model_name):
25
- model_path = hf_hub_download(repo_id=f"Yolov7/{model_name}", filename=f"{model_name}.pt")
26
-
27
- return model_path
28
-
29
-
30
- model_names = [
31
- "yolov7",
32
- "yolov7-e6e",
33
- "yolov7-e6",
34
- ]
35
-
36
- models = {model_name: load_model(model_name) for model_name in model_names}
37
-
38
-
39
- def detect(img,model):
40
- parser = argparse.ArgumentParser()
41
- parser.add_argument('--weights', nargs='+', type=str, default=models[model], help='model.pt path(s)')
42
- parser.add_argument('--source', type=str, default='Inference/', help='source') # file/folder, 0 for webcam
43
- parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
44
- parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
45
- parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
46
- parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
47
- parser.add_argument('--view-img', action='store_true', help='display results')
48
- parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
49
- parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
50
- parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
51
- parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
52
- parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
53
- parser.add_argument('--augment', action='store_true', help='augmented inference')
54
- parser.add_argument('--update', action='store_true', help='update all models')
55
- parser.add_argument('--project', default='runs/detect', help='save results to project/name')
56
- parser.add_argument('--name', default='exp', help='save results to project/name')
57
- parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
58
- parser.add_argument('--trace', action='store_true', help='trace model')
59
- opt = parser.parse_args()
60
- img.save("Inference/test.jpg")
61
- source, weights, view_img, save_txt, imgsz, trace = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size, opt.trace
62
- save_img = True # save inference images
63
- webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
64
- ('rtsp://', 'rtmp://', 'http://', 'https://'))
65
-
66
- # Directories
67
- save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)) # increment run
68
- (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
69
-
70
- # Initialize
71
- set_logging()
72
- device = select_device(opt.device)
73
- half = device.type != 'cpu' # half precision only supported on CUDA
74
 
75
- # Load model
76
- model = attempt_load(weights, map_location=device) # load FP32 model
77
- stride = int(model.stride.max()) # model stride
78
- imgsz = check_img_size(imgsz, s=stride) # check img_size
79
 
80
- if trace:
81
- model = TracedModel(model, device, opt.img_size)
82
 
83
- if half:
84
- model.half() # to FP16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
- # Second-stage classifier
87
- classify = False
88
- if classify:
89
- modelc = load_classifier(name='resnet101', n=2) # initialize
90
- modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()
91
 
92
- # Set Dataloader
93
- vid_path, vid_writer = None, None
94
- if webcam:
95
- view_img = check_imshow()
96
- cudnn.benchmark = True # set True to speed up constant image size inference
97
- dataset = LoadStreams(source, img_size=imgsz, stride=stride)
98
- else:
99
- dataset = LoadImages(source, img_size=imgsz, stride=stride)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
  # Get names and colors
102
  names = model.module.names if hasattr(model, 'module') else model.names
103
- colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]
104
 
105
  # Run inference
106
- if device.type != 'cpu':
107
- model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
108
- t0 = time.time()
109
- for path, img, im0s, vid_cap in dataset:
110
- img = torch.from_numpy(img).to(device)
111
- img = img.half() if half else img.float() # uint8 to fp16/32
112
- img /= 255.0 # 0 - 255 to 0.0 - 1.0
113
- if img.ndimension() == 3:
114
- img = img.unsqueeze(0)
115
-
116
- # Inference
117
- t1 = time_synchronized()
118
- pred = model(img, augment=opt.augment)[0]
119
-
120
- # Apply NMS
121
- pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
122
- t2 = time_synchronized()
123
-
124
- # Apply Classifier
125
- if classify:
126
- pred = apply_classifier(pred, modelc, img, im0s)
127
-
128
- # Process detections
129
- for i, det in enumerate(pred): # detections per image
130
- if webcam: # batch_size >= 1
131
- p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
132
- else:
133
- p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)
134
-
135
- p = Path(p) # to Path
136
- save_path = str(save_dir / p.name) # img.jpg
137
- txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
138
- s += '%gx%g ' % img.shape[2:] # print string
139
- gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
140
- if len(det):
141
- # Rescale boxes from img_size to im0 size
142
- det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
143
-
144
- # Print results
145
- for c in det[:, -1].unique():
146
- n = (det[:, -1] == c).sum() # detections per class
147
- s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
148
-
149
- # Write results
150
- for *xyxy, conf, cls in reversed(det):
151
- if save_txt: # Write to file
152
- xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
153
- line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format
154
- with open(txt_path + '.txt', 'a') as f:
155
- f.write(('%g ' * len(line)).rstrip() % line + '\n')
156
-
157
- if save_img or view_img: # Add bbox to image
158
- label = f'{names[int(cls)]} {conf:.2f}'
159
- plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
160
-
161
- # Print time (inference + NMS)
162
- #print(f'{s}Done. ({t2 - t1:.3f}s)')
163
-
164
- # Stream results
165
- if view_img:
166
- cv2.imshow(str(p), im0)
167
- cv2.waitKey(1) # 1 millisecond
168
-
169
- # Save results (image with detections)
170
- if save_img:
171
- if dataset.mode == 'image':
172
- cv2.imwrite(save_path, im0)
173
- else: # 'video' or 'stream'
174
- if vid_path != save_path: # new video
175
- vid_path = save_path
176
- if isinstance(vid_writer, cv2.VideoWriter):
177
- vid_writer.release() # release previous video writer
178
- if vid_cap: # video
179
- fps = vid_cap.get(cv2.CAP_PROP_FPS)
180
- w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
181
- h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
182
- else: # stream
183
- fps, w, h = 30, im0.shape[1], im0.shape[0]
184
- save_path += '.mp4'
185
- vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
186
- vid_writer.write(im0)
187
-
188
- if save_txt or save_img:
189
- s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
190
- #print(f"Results saved to {save_dir}{s}")
191
-
192
- print(f'Done. ({time.time() - t0:.3f}s)')
193
-
194
- return Image.fromarray(im0[:,:,::-1])
195
-
196
-
197
- gr.Interface(detect,[gr.Image(type="pil"),gr.Dropdown(choices=model_names)], gr.Image(type="pil"),title="Yolov7",examples=[["horses.jpeg", "yolov7"]],description="demo for <a href='https://github.com/WongKinYiu/yolov7' style='text-decoration: underline' target='_blank'>WongKinYiu/yolov7</a> Trainable bag-of-freebies sets new state-of-the-art for real-time object detectors").launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
  import gradio as gr
 
 
 
 
 
 
3
  import cv2
4
+ import numpy as np
5
+ import random
6
+ import numpy as np
 
7
  from models.experimental import attempt_load
8
+ from utils.general import check_img_size, non_max_suppression, \
9
+ scale_coords
 
10
  from utils.plots import plot_one_box
11
+ from utils.torch_utils import time_synchronized
12
+
 
13
  from huggingface_hub import hf_hub_download
14
 
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
 
 
 
 
17
 
 
 
18
 
19
+ def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleup=True, stride=32):
20
+ # Resize and pad image while meeting stride-multiple constraints
21
+ shape = im.shape[:2] # current shape [height, width]
22
+ if isinstance(new_shape, int):
23
+ new_shape = (new_shape, new_shape)
24
+
25
+ # Scale ratio (new / old)
26
+ r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
27
+ if not scaleup: # only scale down, do not scale up (for better val mAP)
28
+ r = min(r, 1.0)
29
+
30
+ # Compute padding
31
+ new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
32
+ dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
33
+
34
+ if auto: # minimum rectangle
35
+ dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
36
 
37
+ dw /= 2 # divide padding into 2 sides
38
+ dh /= 2
 
 
 
39
 
40
+ if shape[::-1] != new_unpad: # resize
41
+ im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
42
+ top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
43
+ left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
44
+ im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
45
+ return im, r, (dw, dh)
46
+
47
+ names = ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
48
+ 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
49
+ 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
50
+ 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
51
+ 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
52
+ 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
53
+ 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
54
+ 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
55
+ 'hair drier', 'toothbrush']
56
+
57
+
58
+ colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]
59
+
60
+
61
+ def detect(img,model,device,iou_threshold=0.45,confidence_threshold=0.25):
62
+ imgsz = 640
63
+ img = np.array(img)
64
+ stride = int(model.stride.max()) # model stride
65
+ imgsz = check_img_size(imgsz, s=stride) # check img_size
66
 
67
  # Get names and colors
68
  names = model.module.names if hasattr(model, 'module') else model.names
 
69
 
70
  # Run inference
71
+ imgs = img.copy() # for NMS
72
+
73
+ image, ratio, dwdh = letterbox(img, auto=False)
74
+ image = image.transpose((2, 0, 1))
75
+ img = torch.from_numpy(image).to(device)
76
+ img = img.float() # uint8 to fp16/32
77
+ img /= 255.0 # 0 - 255 to 0.0 - 1.0
78
+ if img.ndimension() == 3:
79
+ img = img.unsqueeze(0)
80
+
81
+
82
+ # Inference
83
+ t1 = time_synchronized()
84
+ with torch.no_grad(): # Calculating gradients would cause a GPU memory leak
85
+ pred = model(img,augment=True)[0]
86
+ t2 = time_synchronized()
87
+
88
+ # Apply NMS
89
+ pred = non_max_suppression(pred, confidence_threshold, iou_threshold, classes=None, agnostic=True)
90
+ t3 = time_synchronized()
91
+
92
+ for i, det in enumerate(pred): # detections per image
93
+ if len(det):
94
+ # Rescale boxes from img_size to im0 size
95
+ det[:, :4] = scale_coords(img.shape[2:], det[:, :4], imgs.shape).round()
96
+
97
+
98
+ # Write results
99
+ for *xyxy, conf, cls in reversed(det):
100
+ label = f'{names[int(cls)]} {conf:.2f}'
101
+ plot_one_box(xyxy, imgs, label=label, color=colors[int(cls)], line_thickness=2)
102
+
103
+ return imgs
104
+
105
+ def inference(img,model_link,iou_threshold,confidence_threshold):
106
+ print(model_link)
107
+ device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
108
+ # Load model
109
+ model_path = hf_hub_download("shriarul5273/yolov7", str(model_link)+'.pt')
110
+ model = attempt_load(model_path, map_location=device)
111
+ return detect(img,model,device,iou_threshold,confidence_threshold)
112
+
113
+
114
+ def inference2(video,model_link,iou_threshold,confidence_threshold):
115
+ print(model_link)
116
+ device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
117
+ # Load model
118
+ model_path = hf_hub_download("shriarul5273/yolov7", str(model_link)+'.pt')
119
+ model = attempt_load(model_path, map_location=device)
120
+ frames = cv2.VideoCapture(video)
121
+ fps = frames.get(cv2.CAP_PROP_FPS)
122
+ image_size = (int(frames.get(cv2.CAP_PROP_FRAME_WIDTH)),int(frames.get(cv2.CAP_PROP_FRAME_HEIGHT)))
123
+ finalVideo = cv2.VideoWriter('output.mp4',cv2.VideoWriter_fourcc(*'VP90'), fps, image_size)
124
+ p = 1
125
+ while frames.isOpened():
126
+ ret,frame = frames.read()
127
+ if not ret:
128
+ break
129
+ frame = detect(frame,model,device,iou_threshold,confidence_threshold)
130
+ finalVideo.write(frame)
131
+ frames.release()
132
+ finalVideo.release()
133
+ return 'output.mp4'
134
+
135
+
136
+
137
+ examples_images = ['inference/images/horses.jpg',
138
+ 'inference/images/bus.jpg',
139
+ 'inference/images/zidane.jpg']
140
+ examples_videos = ['input_0.mp4','input_1.mp4']
141
+
142
+ models = ['yolov7','yolov7x','yolov7-w6','yolov7-d6','yolov7-e6e']
143
+
144
+ with gr.Blocks() as demo:
145
+ gr.Markdown("## YOLOv7 Inference")
146
+ with gr.Tab("Image"):
147
+ gr.Markdown("## YOLOv7 Inference on Image")
148
+ with gr.Row():
149
+ image_input = gr.Image(type='pil', label="Input Image", source="upload")
150
+ image_output = gr.Image(type='pil', label="Output Image", source="upload")
151
+ image_drop = gr.Dropdown(choices=models,value=models[0])
152
+ image_iou_threshold = gr.Slider(label="IOU Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.45)
153
+ image_conf_threshold = gr.Slider(label="Confidence Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.25)
154
+ gr.Examples(examples=examples_images,inputs=image_input,outputs=image_output)
155
+ text_button = gr.Button("Detect")
156
+ with gr.Tab("Video"):
157
+ gr.Markdown("## YOLOv7 Inference on Video")
158
+ with gr.Row():
159
+ video_input = gr.Video(type='pil', label="Input Image", source="upload")
160
+ video_output = gr.Video(type="pil", label="Output Image",format="mp4")
161
+ video_drop = gr.Dropdown(choices=models,value=models[0])
162
+ video_iou_threshold = gr.Slider(label="IOU Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.45)
163
+ video_conf_threshold = gr.Slider(label="Confidence Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.25)
164
+ gr.Examples(examples=examples_videos,inputs=video_input,outputs=video_output)
165
+ video_button = gr.Button("Detect")
166
+
167
+ with gr.Tab("Webcam Video"):
168
+ gr.Markdown("## YOLOv7 Inference on Webcam Video")
169
+ gr.Markdown("Coming Soon")
170
+
171
+ text_button.click(inference, inputs=[image_input,image_drop,
172
+ image_iou_threshold,image_conf_threshold],
173
+ outputs=image_output)
174
+ video_button.click(inference2, inputs=[video_input,video_drop,
175
+ video_iou_threshold,video_conf_threshold],
176
+ outputs=video_output)
177
+
178
+ demo.launch()
input_0.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0305b8ba574b0b26c8d21b70dbd80aacbba13e813a99f5c4675982063ebd18a3
3
+ size 1103987
input_1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:103c54e60a7abf381741b4bcc5e696f5d200fc2a4ff259cc779bbd511dc2dae1
3
+ size 1792081