Spaces:
Runtime error
Runtime error
Upload 3 files
#8
by
shriarul5273
- opened
- .gitattributes +2 -0
- app.py +161 -180
- input_0.mp4 +3 -0
- 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
|
10 |
-
import
|
11 |
-
|
12 |
-
|
13 |
from models.experimental import attempt_load
|
14 |
-
from utils.
|
15 |
-
|
16 |
-
scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path
|
17 |
from utils.plots import plot_one_box
|
18 |
-
from utils.torch_utils import
|
19 |
-
|
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 |
-
|
84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
|
86 |
-
#
|
87 |
-
|
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 |
-
#
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|