nathanjc commited on
Commit
7d6bf72
·
verified ·
1 Parent(s): d8a39b5

Update app.py

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