BeMerciless commited on
Commit
e4f09ea
1 Parent(s): 7fba7be

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +171 -0
  2. best.pt +3 -0
  3. requirements.txt +17 -0
app.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import argparse
3
+ import gradio as gr
4
+ from PIL import Image
5
+ from numpy import random
6
+ from pathlib import Path
7
+ import os
8
+ import time
9
+ import torch.backends.cudnn as cudnn
10
+ from models.experimental import attempt_load
11
+ import cv2
12
+ from utils.datasets import LoadStreams, LoadImages
13
+ from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier,scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path
14
+ from utils.plots import plot_one_box
15
+ from utils.torch_utils import select_device, load_classifier, time_synchronized, TracedModel
16
+
17
+
18
+ os.system('git clone https://github.com/WongKinYiu/yolov7')
19
+ os.system('wget https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7.pt')
20
+ #os.system('wget https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-mask.pt')
21
+
22
+ #model='best'
23
+ def Custom_detect(img,mode):
24
+ if mode=='Custom-Detection':
25
+ model='best'
26
+ #if mode=='Instance-Segmentation':
27
+ # model='yolov7-mask'
28
+ if mode=='Yolov7-model-detection':
29
+ model='yolov7'
30
+
31
+ parser = argparse.ArgumentParser()
32
+ parser.add_argument('--weights', nargs='+', type=str, default=model+".pt", help='model.pt path(s)')
33
+ parser.add_argument('--source', type=str, default='Temp_files/', help='source')
34
+ parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
35
+ parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
36
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
37
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
38
+ parser.add_argument('--view-img', action='store_true', help='display results')
39
+ parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
40
+ parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
41
+ parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
42
+ parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
43
+ parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
44
+ parser.add_argument('--augment', action='store_true', help='augmented inference')
45
+ parser.add_argument('--update', action='store_true', help='update all models')
46
+ parser.add_argument('--project', default='runs/detect', help='save results to project/name')
47
+ parser.add_argument('--name', default='exp', help='save results to project/name')
48
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
49
+ parser.add_argument('--trace', action='store_true', help='trace model')
50
+ opt = parser.parse_args()
51
+ img.save("Temp_files/test.jpg")
52
+ source, weights, view_img, save_txt, imgsz, trace = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size, opt.trace
53
+ save_img = True
54
+ webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
55
+ save_dir = Path(increment_path(Path(opt.project)/opt.name,exist_ok=opt.exist_ok))
56
+
57
+ (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)
58
+ set_logging()
59
+ device = select_device(opt.device)
60
+ half = device.type != 'cpu'
61
+ model = attempt_load(weights, map_location=device)
62
+ stride = int(model.stride.max())
63
+ imgsz = check_img_size(imgsz, s=stride)
64
+ if trace:
65
+ model = TracedModel(model, device, opt.img_size)
66
+ if half:
67
+ model.half()
68
+
69
+ classify = False
70
+ if classify:
71
+ modelc = load_classifier(name='resnet101', n=2) # initialize
72
+ modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()
73
+ vid_path, vid_writer = None, None
74
+ if webcam:
75
+ view_img = check_imshow()
76
+ cudnn.benchmark = True
77
+ dataset = LoadStreams(source, img_size=imgsz, stride=stride)
78
+ else:
79
+ dataset = LoadImages(source, img_size=imgsz, stride=stride)
80
+ names = model.module.names if hasattr(model, 'module') else model.names
81
+ colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]
82
+ if device.type != 'cpu':
83
+ model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters())))
84
+ t0 = time.time()
85
+ for path, img, im0s, vid_cap in dataset:
86
+ img = torch.from_numpy(img).to(device)
87
+ img = img.half() if half else img.float()
88
+ img /= 255.0
89
+ if img.ndimension() == 3:
90
+ img = img.unsqueeze(0)
91
+
92
+ # Inference
93
+ t1 = time_synchronized()
94
+ pred = model(img, augment=opt.augment)[0]
95
+
96
+ pred = non_max_suppression(pred,opt.conf_thres,opt.iou_thres,classes=opt.classes, agnostic=opt.agnostic_nms)
97
+ t2 = time_synchronized()
98
+
99
+
100
+ # Apply Classifier
101
+ if classify:
102
+ pred = apply_classifier(pred, modelc, img, im0s)
103
+
104
+ for i, det in enumerate(pred):
105
+ if webcam:
106
+ p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
107
+ else:
108
+ p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)
109
+
110
+ p = Path(p)
111
+ save_path = str(save_dir / p.name)
112
+ txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
113
+ s += '%gx%g ' % img.shape[2:]
114
+ gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]
115
+ if len(det):
116
+ det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
117
+
118
+
119
+ for c in det[:, -1].unique():
120
+ n = (det[:, -1] == c).sum()
121
+ s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "
122
+
123
+
124
+ for *xyxy, conf, cls in reversed(det):
125
+ if save_txt:
126
+ xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()
127
+ line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh)
128
+ with open(txt_path + '.txt', 'a') as f:
129
+ f.write(('%g ' * len(line)).rstrip() % line + '\n')
130
+
131
+ if save_img or view_img:
132
+ label = f'{names[int(cls)]} {conf:.2f}'
133
+ plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=2)
134
+ if view_img:
135
+ cv2.imshow(str(p), im0)
136
+ cv2.waitKey(1)
137
+
138
+ if save_img:
139
+ if dataset.mode == 'image':
140
+ cv2.imwrite(save_path, im0)
141
+ else:
142
+ if vid_path != save_path:
143
+ vid_path = save_path
144
+ if isinstance(vid_writer, cv2.VideoWriter):
145
+ vid_writer.release()
146
+ if vid_cap:
147
+ fps = vid_cap.get(cv2.CAP_PROP_FPS)
148
+ w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
149
+ h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
150
+ else:
151
+ fps, w, h = 30, im0.shape[1], im0.shape[0]
152
+ save_path += '.mp4'
153
+ vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
154
+ vid_writer.write(im0)
155
+
156
+ if save_txt or save_img:
157
+ s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
158
+
159
+ print(f'Done. ({time.time() - t0:.3f}s)')
160
+
161
+ return Image.fromarray(im0[:,:,::-1])
162
+ inp = gr.Image(type="pil")
163
+ #"Custom-Detection","Yolov7-model-detection"
164
+ inp2= gr.Dropdown(choices=['Custom-Detection','Yolov7-model-detection'])
165
+ output = gr.Image(type="pil")
166
+
167
+ examples=[["Examples/Image1.jpg","Image1"],["Examples/Image14.jpg","Image14"],["Examples/Image32.jpg","Image32"]]
168
+
169
+ io=gr.Interface(fn=Custom_detect, inputs=[inp,inp2], outputs=output, title='Vehicle Detection With Custom YOLOv7')
170
+ io.launch()
171
+
best.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:684df6fb2d37bdda4d82b14f35a26d0bb701abc92ac2782606d680e87714ff87
3
+ size 74839177
requirements.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ matplotlib>=3.2.2
2
+ numpy>=1.18.5
3
+ opencv-python>=4.1.1
4
+ Pillow>=7.1.2
5
+ PyYAML>=5.3.1
6
+ requests>=2.23.0
7
+ scipy>=1.4.1
8
+ torch>=1.7.0,!=1.12.0
9
+ torchvision>=0.8.1,!=0.13.0
10
+ tqdm>=4.41.0
11
+ protobuf<4.21.3
12
+
13
+
14
+ tensorboard>=2.4.1
15
+
16
+ pandas>=1.1.4
17
+ seaborn>=0.11.0