akhaliq HF staff commited on
Commit
2e3d753
β€’
1 Parent(s): e20a59b

add gradio demo

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