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