nathanjc commited on
Commit
ddf04e3
·
1 Parent(s): 2f472db

Update app.py

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