nathanjc commited on
Commit
20215ab
·
1 Parent(s): be423c9

Create app.py

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