Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -8,7 +8,7 @@ import gradio as gr
|
|
8 |
|
9 |
def object_detection(image):
|
10 |
image = image.convert("RGB")
|
11 |
-
image = image.resize((
|
12 |
image = np.array(image).transpose((2, 0, 1))
|
13 |
image = np.expand_dims(image, axis=0).astype(np.float32)
|
14 |
|
@@ -32,4 +32,227 @@ with gr.Blocks() as demo:
|
|
32 |
|
33 |
image_button.click(object_detection,inputs=image_input,outputs=[image_output,image_text])
|
34 |
demo.close()
|
35 |
-
demo.launch(server_port=9090)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
def object_detection(image):
|
10 |
image = image.convert("RGB")
|
11 |
+
image = image.resize((640, 640))
|
12 |
image = np.array(image).transpose((2, 0, 1))
|
13 |
image = np.expand_dims(image, axis=0).astype(np.float32)
|
14 |
|
|
|
32 |
|
33 |
image_button.click(object_detection,inputs=image_input,outputs=[image_output,image_text])
|
34 |
demo.close()
|
35 |
+
demo.launch(server_port=9090)import os
|
36 |
+
import sys
|
37 |
+
import argparse
|
38 |
+
import time
|
39 |
+
from pathlib import Path
|
40 |
+
import pandas as pd
|
41 |
+
|
42 |
+
import gradio as gr
|
43 |
+
import cv2
|
44 |
+
from PIL import Image
|
45 |
+
import torch
|
46 |
+
import torch.backends.cudnn as cudnn
|
47 |
+
from numpy import random
|
48 |
+
|
49 |
+
BASE_DIR = "/home/user/app"
|
50 |
+
os.chdir(BASE_DIR)
|
51 |
+
os.makedirs(f"{BASE_DIR}/input",exist_ok=True)
|
52 |
+
os.system(f"git clone https://github.com/WongKinYiu/yolov7.git {BASE_DIR}/yolov7")
|
53 |
+
sys.path.append(f'{BASE_DIR}/yolov7')
|
54 |
+
|
55 |
+
def detect(opt, save_img=False):
|
56 |
+
from models.experimental import attempt_load
|
57 |
+
from utils.datasets import LoadStreams, LoadImages
|
58 |
+
from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \
|
59 |
+
scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path
|
60 |
+
from utils.plots import plot_one_box
|
61 |
+
from utils.torch_utils import select_device, load_classifier, time_synchronized, TracedModel
|
62 |
+
|
63 |
+
bbox = {}
|
64 |
+
source, weights, view_img, save_txt, imgsz, trace = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size, not opt.no_trace
|
65 |
+
save_img = not opt.nosave and not source.endswith('.txt') # save inference images
|
66 |
+
webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
|
67 |
+
('rtsp://', 'rtmp://', 'http://', 'https://'))
|
68 |
+
|
69 |
+
# Directories
|
70 |
+
save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)) # increment run
|
71 |
+
(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
|
72 |
+
|
73 |
+
# Initialize
|
74 |
+
set_logging()
|
75 |
+
device = select_device(opt.device)
|
76 |
+
half = device.type != 'cpu' # half precision only supported on CUDA
|
77 |
+
|
78 |
+
# Load model
|
79 |
+
model = attempt_load(weights, map_location=device) # load FP32 model
|
80 |
+
stride = int(model.stride.max()) # model stride
|
81 |
+
imgsz = check_img_size(imgsz, s=stride) # check img_size
|
82 |
+
|
83 |
+
if trace:
|
84 |
+
model = TracedModel(model, device, opt.img_size)
|
85 |
+
|
86 |
+
if half:
|
87 |
+
model.half() # to FP16
|
88 |
+
|
89 |
+
# Second-stage classifier
|
90 |
+
classify = False
|
91 |
+
if classify:
|
92 |
+
modelc = load_classifier(name='resnet101', n=2) # initialize
|
93 |
+
modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()
|
94 |
+
|
95 |
+
# Set Dataloader
|
96 |
+
vid_path, vid_writer = None, None
|
97 |
+
if webcam:
|
98 |
+
view_img = check_imshow()
|
99 |
+
cudnn.benchmark = True # set True to speed up constant image size inference
|
100 |
+
dataset = LoadStreams(source, img_size=imgsz, stride=stride)
|
101 |
+
else:
|
102 |
+
dataset = LoadImages(source, img_size=imgsz, stride=stride)
|
103 |
+
|
104 |
+
# Get names and colors
|
105 |
+
names = model.module.names if hasattr(model, 'module') else model.names
|
106 |
+
colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]
|
107 |
+
|
108 |
+
# Run inference
|
109 |
+
if device.type != 'cpu':
|
110 |
+
model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
|
111 |
+
old_img_w = old_img_h = imgsz
|
112 |
+
old_img_b = 1
|
113 |
+
|
114 |
+
t0 = time.time()
|
115 |
+
for path, img, im0s, vid_cap in dataset:
|
116 |
+
img = torch.from_numpy(img).to(device)
|
117 |
+
img = img.half() if half else img.float() # uint8 to fp16/32
|
118 |
+
img /= 255.0 # 0 - 255 to 0.0 - 1.0
|
119 |
+
if img.ndimension() == 3:
|
120 |
+
img = img.unsqueeze(0)
|
121 |
+
|
122 |
+
# Warmup
|
123 |
+
if device.type != 'cpu' and (old_img_b != img.shape[0] or old_img_h != img.shape[2] or old_img_w != img.shape[3]):
|
124 |
+
old_img_b = img.shape[0]
|
125 |
+
old_img_h = img.shape[2]
|
126 |
+
old_img_w = img.shape[3]
|
127 |
+
for i in range(3):
|
128 |
+
model(img, augment=opt.augment)[0]
|
129 |
+
|
130 |
+
# Inference
|
131 |
+
t1 = time_synchronized()
|
132 |
+
with torch.no_grad(): # Calculating gradients would cause a GPU memory leak
|
133 |
+
pred = model(img, augment=opt.augment)[0]
|
134 |
+
t2 = time_synchronized()
|
135 |
+
|
136 |
+
# Apply NMS
|
137 |
+
pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
|
138 |
+
t3 = time_synchronized()
|
139 |
+
|
140 |
+
# Apply Classifier
|
141 |
+
if classify:
|
142 |
+
pred = apply_classifier(pred, modelc, img, im0s)
|
143 |
+
|
144 |
+
# Process detections
|
145 |
+
for i, det in enumerate(pred): # detections per image
|
146 |
+
if webcam: # batch_size >= 1
|
147 |
+
p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
|
148 |
+
else:
|
149 |
+
p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)
|
150 |
+
|
151 |
+
p = Path(p) # to Path
|
152 |
+
save_path = str(save_dir / p.name) # img.jpg
|
153 |
+
txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
|
154 |
+
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
|
155 |
+
if len(det):
|
156 |
+
# Rescale boxes from img_size to im0 size
|
157 |
+
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
|
158 |
+
# print(f"BOXES ---->>>> {det[:, :4]}")
|
159 |
+
bbox[f"{txt_path.split('/')[4]}"]=(det[:, :4]).numpy()
|
160 |
+
|
161 |
+
# Print results
|
162 |
+
for c in det[:, -1].unique():
|
163 |
+
n = (det[:, -1] == c).sum() # detections per class
|
164 |
+
s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
|
165 |
+
|
166 |
+
# Write results
|
167 |
+
for *xyxy, conf, cls in reversed(det):
|
168 |
+
if save_txt: # Write to file
|
169 |
+
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
|
170 |
+
line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format
|
171 |
+
with open(txt_path + '.txt', 'a') as f:
|
172 |
+
f.write(('%g ' * len(line)).rstrip() % line + '\n')
|
173 |
+
|
174 |
+
if save_img or view_img: # Add bbox to image
|
175 |
+
label = f'{names[int(cls)]} {conf:.2f}'
|
176 |
+
plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=1)
|
177 |
+
|
178 |
+
# Print time (inference + NMS)
|
179 |
+
print(f'{s}Done. ({(1E3 * (t2 - t1)):.1f}ms) Inference, ({(1E3 * (t3 - t2)):.1f}ms) NMS')
|
180 |
+
|
181 |
+
# Stream results
|
182 |
+
# if view_img:
|
183 |
+
# cv2.imshow(str(p), im0)
|
184 |
+
# cv2.waitKey(1) # 1 millisecond
|
185 |
+
|
186 |
+
# Save results (image with detections)
|
187 |
+
if save_img:
|
188 |
+
if dataset.mode == 'image':
|
189 |
+
# Image.fromarray(im0).show()
|
190 |
+
cv2.imwrite(save_path, im0)
|
191 |
+
print(f" The image with the result is saved in: {save_path}")
|
192 |
+
# else: # 'video' or 'stream'
|
193 |
+
# if vid_path != save_path: # new video
|
194 |
+
# vid_path = save_path
|
195 |
+
# if isinstance(vid_writer, cv2.VideoWriter):
|
196 |
+
# vid_writer.release() # release previous video writer
|
197 |
+
# if vid_cap: # video
|
198 |
+
# fps = vid_cap.get(cv2.CAP_PROP_FPS)
|
199 |
+
# w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
200 |
+
# h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
201 |
+
# else: # stream
|
202 |
+
# fps, w, h = 30, im0.shape[1], im0.shape[0]
|
203 |
+
# save_path += '.mp4'
|
204 |
+
# vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
|
205 |
+
# vid_writer.write(im0)
|
206 |
+
|
207 |
+
if save_txt or save_img:
|
208 |
+
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
|
209 |
+
#print(f"Results saved to {save_dir}{s}")
|
210 |
+
|
211 |
+
print(f'Done. ({time.time() - t0:.3f}s)')
|
212 |
+
return bbox,save_path
|
213 |
+
|
214 |
+
class options:
|
215 |
+
def __init__(self, weights, source, img_size=640, conf_thres=0.1, iou_thres=0.45, device='',
|
216 |
+
view_img=False, save_txt=False, save_conf=False, nosave=False, classes=None,
|
217 |
+
agnostic_nms=False, augment=False, update=False, project='runs/detect', name='exp',
|
218 |
+
exist_ok=False, no_trace=False):
|
219 |
+
self.weights=weights
|
220 |
+
self.source=source
|
221 |
+
self.img_size=img_size
|
222 |
+
self.conf_thres=conf_thres
|
223 |
+
self.iou_thres=iou_thres
|
224 |
+
self.device=device
|
225 |
+
self.view_img=view_img
|
226 |
+
self.save_txt=save_txt
|
227 |
+
self.save_conf=save_conf
|
228 |
+
self.nosave=nosave
|
229 |
+
self.classes=classes
|
230 |
+
self.agnostic_nms=agnostic_nms
|
231 |
+
self.augment=augment
|
232 |
+
self.update=update
|
233 |
+
self.project=project
|
234 |
+
self.name=name
|
235 |
+
self.exist_ok=exist_ok
|
236 |
+
self.no_trace=no_trace
|
237 |
+
|
238 |
+
def get_output(image):
|
239 |
+
image.save(f"{BASE_DIR}/input/image.jpg")
|
240 |
+
source = f"{BASE_DIR}/input"
|
241 |
+
opt = options(weights='logo_detection.pt',source=source)
|
242 |
+
bbox = None
|
243 |
+
with torch.no_grad():
|
244 |
+
# if opt.update: # update all models (to fix SourceChangeWarning)
|
245 |
+
# for opt.weights in ['yolov7.pt']:
|
246 |
+
# bbox,output_path = detect(opt)
|
247 |
+
# strip_optimizer(opt.weights)
|
248 |
+
# else:
|
249 |
+
bbox,output_path = detect(opt)
|
250 |
+
if os.path.exists(output_path):
|
251 |
+
return Image.open(output_path)
|
252 |
+
else:
|
253 |
+
return image
|
254 |
+
|
255 |
+
gr.Interface(fn=get_output,
|
256 |
+
inputs=gr.Image(type = "pil", label="Your image"),
|
257 |
+
outputs="image"
|
258 |
+
).launch(debug=True)
|