Spaces:
Build error
Build error
owaiskha9654
commited on
Commit
•
77138dd
1
Parent(s):
d0871c3
Update app.py
Browse files
app.py
CHANGED
@@ -1,34 +1,27 @@
|
|
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
|
|
|
|
|
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 |
-
|
|
|
24 |
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
def detect_Custom(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')
|
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')
|
@@ -48,57 +41,37 @@ def detect_Custom(img,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
|
52 |
webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
|
53 |
('rtsp://', 'rtmp://', 'http://', 'https://'))
|
54 |
-
|
55 |
-
|
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'
|
63 |
-
|
64 |
-
|
65 |
-
|
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()
|
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
|
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())))
|
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()
|
101 |
-
img /= 255.0
|
102 |
if img.ndimension() == 3:
|
103 |
img = img.unsqueeze(0)
|
104 |
|
@@ -106,69 +79,60 @@ def detect_Custom(img,model):
|
|
106 |
t1 = time_synchronized()
|
107 |
pred = model(img, augment=opt.augment)[0]
|
108 |
|
109 |
-
|
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 |
-
|
118 |
-
|
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)
|
125 |
-
save_path = str(save_dir / p.name)
|
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:]
|
128 |
-
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]
|
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 |
-
|
134 |
for c in det[:, -1].unique():
|
135 |
-
n = (det[:, -1] == c).sum()
|
136 |
-
s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "
|
137 |
|
138 |
-
|
139 |
for *xyxy, conf, cls in reversed(det):
|
140 |
-
if save_txt:
|
141 |
-
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()
|
142 |
-
line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh)
|
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:
|
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)
|
157 |
|
158 |
-
# Save results (image with detections)
|
159 |
if save_img:
|
160 |
if dataset.mode == 'image':
|
161 |
cv2.imwrite(save_path, im0)
|
162 |
-
else:
|
163 |
-
if vid_path != save_path:
|
164 |
vid_path = save_path
|
165 |
if isinstance(vid_writer, cv2.VideoWriter):
|
166 |
-
vid_writer.release()
|
167 |
-
if vid_cap:
|
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:
|
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))
|
@@ -176,7 +140,6 @@ def detect_Custom(img,model):
|
|
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 |
|
@@ -184,10 +147,10 @@ def detect_Custom(img,model):
|
|
184 |
|
185 |
|
186 |
|
187 |
-
description="Custom Training Performed on Kaggle <a href='https://www.kaggle.com/code/owaiskhan9654/training-yolov7-on-kaggle-on-custom-dataset/notebook' style='text-decoration: underline' target='_blank'>Link</a>
|
188 |
|
189 |
text1 = (
|
190 |
-
"<center>
|
191 |
|
192 |
"<center> Model Trained Kaggle Kernel <a href=\"https://www.kaggle.com/code/owaiskhan9654/training-yolov7-on-kaggle-on-custom-dataset/notebook\">Link</a> <br></center>"
|
193 |
|
@@ -198,4 +161,6 @@ text1 = (
|
|
198 |
|
199 |
examples1=[["Image1.jpeg", "Yolo_v7_Custom_trained_By_Owais"],["Image2.jpeg", "Yolo_v7_Custom_trained_By_Owais"],["Image3.jpeg", "Yolo_v7_Custom_trained_By_Owais",],["Image4.jpeg", "Yolo_v7_Custom_trained_By_Owais"],["Image5.jpeg", "Yolo_v7_Custom_trained_By_Owais"],["Image6.jpeg", "Yolo_v7_Custom_trained_By_Owais"],["horses.jpeg", "yolov7"],["horses.jpeg", "yolov7-e6"]]
|
200 |
|
201 |
-
|
|
|
|
|
|
|
|
1 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
import cv2
|
3 |
+
import time
|
4 |
import torch
|
5 |
+
import argparse
|
6 |
+
import gradio as gr
|
7 |
+
from PIL import Image
|
8 |
from numpy import random
|
9 |
+
from pathlib import Path
|
10 |
+
import torch.backends.cudnn as cudnn
|
11 |
from models.experimental import attempt_load
|
12 |
+
|
13 |
from utils.datasets import LoadStreams, LoadImages
|
14 |
from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \
|
15 |
scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path
|
16 |
from utils.plots import plot_one_box
|
17 |
from utils.torch_utils import select_device, load_classifier, time_synchronized, TracedModel
|
18 |
+
os.system("wget https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7.pt")
|
19 |
+
os.system("wget https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-e6.pt")
|
20 |
|
|
|
|
|
|
|
21 |
def detect_Custom(img,model):
|
22 |
parser = argparse.ArgumentParser()
|
23 |
parser.add_argument('--weights', nargs='+', type=str, default=model+".pt", help='model.pt path(s)')
|
24 |
+
parser.add_argument('--source', type=str, default='Inference/', help='source')
|
25 |
parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
|
26 |
parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
|
27 |
parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
|
|
|
41 |
opt = parser.parse_args()
|
42 |
img.save("Inference/test.jpg")
|
43 |
source, weights, view_img, save_txt, imgsz, trace = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size, opt.trace
|
44 |
+
save_img = True
|
45 |
webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
|
46 |
('rtsp://', 'rtmp://', 'http://', 'https://'))
|
47 |
+
save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok))
|
48 |
+
(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
|
|
|
49 |
set_logging()
|
50 |
device = select_device(opt.device)
|
51 |
+
half = device.type != 'cpu'
|
52 |
+
model = attempt_load(weights, map_location=device)
|
53 |
+
stride = int(model.stride.max())
|
54 |
+
imgsz = check_img_size(imgsz, s=stride)
|
|
|
|
|
|
|
55 |
if trace:
|
56 |
model = TracedModel(model, device, opt.img_size)
|
|
|
57 |
if half:
|
58 |
+
model.half()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
vid_path, vid_writer = None, None
|
60 |
if webcam:
|
61 |
view_img = check_imshow()
|
62 |
+
cudnn.benchmark = True
|
63 |
dataset = LoadStreams(source, img_size=imgsz, stride=stride)
|
64 |
else:
|
65 |
dataset = LoadImages(source, img_size=imgsz, stride=stride)
|
|
|
|
|
66 |
names = model.module.names if hasattr(model, 'module') else model.names
|
67 |
colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]
|
|
|
|
|
68 |
if device.type != 'cpu':
|
69 |
+
model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters())))
|
70 |
t0 = time.time()
|
71 |
for path, img, im0s, vid_cap in dataset:
|
72 |
img = torch.from_numpy(img).to(device)
|
73 |
+
img = img.half() if half else img.float()
|
74 |
+
img /= 255.0
|
75 |
if img.ndimension() == 3:
|
76 |
img = img.unsqueeze(0)
|
77 |
|
|
|
79 |
t1 = time_synchronized()
|
80 |
pred = model(img, augment=opt.augment)[0]
|
81 |
|
82 |
+
|
83 |
pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
|
84 |
t2 = time_synchronized()
|
85 |
|
|
|
86 |
if classify:
|
87 |
pred = apply_classifier(pred, modelc, img, im0s)
|
88 |
|
89 |
+
for i, det in enumerate(pred):
|
90 |
+
if webcam:
|
|
|
91 |
p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
|
92 |
else:
|
93 |
p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)
|
94 |
|
95 |
+
p = Path(p)
|
96 |
+
save_path = str(save_dir / p.name)
|
97 |
txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
|
98 |
+
s += '%gx%g ' % img.shape[2:]
|
99 |
+
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]
|
100 |
if len(det):
|
|
|
101 |
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
|
102 |
|
103 |
+
|
104 |
for c in det[:, -1].unique():
|
105 |
+
n = (det[:, -1] == c).sum()
|
106 |
+
s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "
|
107 |
|
108 |
+
|
109 |
for *xyxy, conf, cls in reversed(det):
|
110 |
+
if save_txt:
|
111 |
+
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()
|
112 |
+
line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh)
|
113 |
with open(txt_path + '.txt', 'a') as f:
|
114 |
f.write(('%g ' * len(line)).rstrip() % line + '\n')
|
115 |
|
116 |
+
if save_img or view_img:
|
117 |
label = f'{names[int(cls)]} {conf:.2f}'
|
118 |
plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
|
|
|
|
|
|
|
|
|
|
|
119 |
if view_img:
|
120 |
cv2.imshow(str(p), im0)
|
121 |
+
cv2.waitKey(1)
|
122 |
|
|
|
123 |
if save_img:
|
124 |
if dataset.mode == 'image':
|
125 |
cv2.imwrite(save_path, im0)
|
126 |
+
else:
|
127 |
+
if vid_path != save_path:
|
128 |
vid_path = save_path
|
129 |
if isinstance(vid_writer, cv2.VideoWriter):
|
130 |
+
vid_writer.release()
|
131 |
+
if vid_cap:
|
132 |
fps = vid_cap.get(cv2.CAP_PROP_FPS)
|
133 |
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
134 |
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
135 |
+
else:
|
136 |
fps, w, h = 30, im0.shape[1], im0.shape[0]
|
137 |
save_path += '.mp4'
|
138 |
vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
|
|
|
140 |
|
141 |
if save_txt or save_img:
|
142 |
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
|
|
|
143 |
|
144 |
print(f'Done. ({time.time() - t0:.3f}s)')
|
145 |
|
|
|
147 |
|
148 |
|
149 |
|
150 |
+
description="<center>Custom Training Performed on Kaggle <a href='https://www.kaggle.com/code/owaiskhan9654/training-yolov7-on-kaggle-on-custom-dataset/notebook' style='text-decoration: underline' target='_blank'>Link</a> </center><br> <center>Trainable bag-of-freebies sets new state-of-the-art for real-time object detectors </center> <br> <center>Also Please use <b>Images with .jpeg</b> because Yolo V7 Model is trained on GPU and while inferencing default CPU has been implemented</center>"
|
151 |
|
152 |
text1 = (
|
153 |
+
"<center>Model Trained by: Owais Ahmad Data Scientist at <b> Thoucentric </b> <a href=\"https://www.linkedin.com/in/owaiskhan9654/\">Visit Profile</a> <br></center>"
|
154 |
|
155 |
"<center> Model Trained Kaggle Kernel <a href=\"https://www.kaggle.com/code/owaiskhan9654/training-yolov7-on-kaggle-on-custom-dataset/notebook\">Link</a> <br></center>"
|
156 |
|
|
|
161 |
|
162 |
examples1=[["Image1.jpeg", "Yolo_v7_Custom_trained_By_Owais"],["Image2.jpeg", "Yolo_v7_Custom_trained_By_Owais"],["Image3.jpeg", "Yolo_v7_Custom_trained_By_Owais",],["Image4.jpeg", "Yolo_v7_Custom_trained_By_Owais"],["Image5.jpeg", "Yolo_v7_Custom_trained_By_Owais"],["Image6.jpeg", "Yolo_v7_Custom_trained_By_Owais"],["horses.jpeg", "yolov7"],["horses.jpeg", "yolov7-e6"]]
|
163 |
|
164 |
+
Title="<center>Yolov7 Custom Trained by <a href='https://www.linkedin.com/in/owaiskhan9654/' style='text-decoration: underline' target='_blank'>Owais Ahmad</center></a>"
|
165 |
+
|
166 |
+
gr.Interface(detect_Custom,[gr.Image(type="pil"),gr.Dropdown(default="Yolo_v7_Custom_trained_By_Owais",choices=["Yolo_v7_Custom_trained_By_Owais","yolov7","yolov7-e6"])],gr.Image(type="pil"),title=,examples=examples1,description=description,article=text1,cache_examples=False).launch()
|