Sa-m commited on
Commit
0afe34f
·
1 Parent(s): cf2ba10

Create new file

Browse files
Files changed (1) hide show
  1. app.py +162 -0
app.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
20
+
21
+
22
+ def Custom_detect(img):
23
+ model='best'
24
+ parser = argparse.ArgumentParser()
25
+ parser.add_argument('--weights', nargs='+', type=str, default=model+".pt", help='model.pt path(s)')
26
+ parser.add_argument('--source', type=str, default='Temp_file/', help='source')
27
+ parser.add_argument('--img-size', type=int, default=100, help='inference size (pixels)')
28
+ parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
29
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
30
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
31
+ parser.add_argument('--view-img', action='store_true', help='display results')
32
+ parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
33
+ parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
34
+ parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
35
+ parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
36
+ parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
37
+ parser.add_argument('--augment', action='store_true', help='augmented inference')
38
+ parser.add_argument('--update', action='store_true', help='update all models')
39
+ parser.add_argument('--project', default='runs/detect', help='save results to project/name')
40
+ parser.add_argument('--name', default='exp', help='save results to project/name')
41
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
42
+ parser.add_argument('--trace', action='store_true', help='trace model')
43
+ opt = parser.parse_args()
44
+ img.save("Temp_file/test.jpg")
45
+ source, weights, view_img, save_txt, imgsz, trace = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size, opt.trace
46
+ save_img = True
47
+ webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
48
+ save_dir = Path(increment_path(Path(opt.project)/opt.name,exist_ok=opt.exist_ok))
49
+
50
+ (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)
51
+ set_logging()
52
+ device = select_device(opt.device)
53
+ half = device.type != 'cpu'
54
+ model = attempt_load(weights, map_location=device)
55
+ stride = int(model.stride.max())
56
+ imgsz = check_img_size(imgsz, s=stride)
57
+ if trace:
58
+ model = TracedModel(model, device, opt.img_size)
59
+ if half:
60
+ model.half()
61
+
62
+ classify = False
63
+ if classify:
64
+ modelc = load_classifier(name='resnet101', n=2) # initialize
65
+ modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()
66
+ vid_path, vid_writer = None, None
67
+ if webcam:
68
+ view_img = check_imshow()
69
+ cudnn.benchmark = True
70
+ dataset = LoadStreams(source, img_size=imgsz, stride=stride)
71
+ else:
72
+ dataset = LoadImages(source, img_size=imgsz, stride=stride)
73
+ names = model.module.names if hasattr(model, 'module') else model.names
74
+ colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]
75
+ if device.type != 'cpu':
76
+ model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters())))
77
+ t0 = time.time()
78
+ for path, img, im0s, vid_cap in dataset:
79
+ img = torch.from_numpy(img).to(device)
80
+ img = img.half() if half else img.float()
81
+ img /= 255.0
82
+ if img.ndimension() == 3:
83
+ img = img.unsqueeze(0)
84
+
85
+ # Inference
86
+ t1 = time_synchronized()
87
+ pred = model(img, augment=opt.augment)[0]
88
+
89
+ pred = non_max_suppression(pred,opt.conf_thres,opt.iou_thres,classes=opt.classes, agnostic=opt.agnostic_nms)
90
+ t2 = time_synchronized()
91
+
92
+
93
+ # Apply Classifier
94
+ if classify:
95
+ pred = apply_classifier(pred, modelc, img, im0s)
96
+
97
+ for i, det in enumerate(pred):
98
+ if webcam:
99
+ p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
100
+ else:
101
+ p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)
102
+
103
+ p = Path(p)
104
+ save_path = str(save_dir / p.name)
105
+ txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
106
+ s += '%gx%g ' % img.shape[2:]
107
+ gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]
108
+ if len(det):
109
+ det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
110
+
111
+
112
+ for c in det[:, -1].unique():
113
+ n = (det[:, -1] == c).sum()
114
+ s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "
115
+
116
+
117
+ for *xyxy, conf, cls in reversed(det):
118
+ if save_txt:
119
+ xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()
120
+ line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh)
121
+ with open(txt_path + '.txt', 'a') as f:
122
+ f.write(('%g ' * len(line)).rstrip() % line + '\n')
123
+
124
+ if save_img or view_img:
125
+ label = f'{names[int(cls)]} {conf:.2f}'
126
+ plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
127
+ if view_img:
128
+ cv2.imshow(str(p), im0)
129
+ cv2.waitKey(1)
130
+
131
+ if save_img:
132
+ if dataset.mode == 'image':
133
+ cv2.imwrite(save_path, im0)
134
+ else:
135
+ if vid_path != save_path:
136
+ vid_path = save_path
137
+ if isinstance(vid_writer, cv2.VideoWriter):
138
+ vid_writer.release()
139
+ if vid_cap:
140
+ fps = vid_cap.get(cv2.CAP_PROP_FPS)
141
+ w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
142
+ h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
143
+ else:
144
+ fps, w, h = 30, im0.shape[1], im0.shape[0]
145
+ save_path += '.mp4'
146
+ vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
147
+ vid_writer.write(im0)
148
+
149
+ if save_txt or save_img:
150
+ s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
151
+
152
+ print(f'Done. ({time.time() - t0:.3f}s)')
153
+
154
+ return Image.fromarray(im0[:,:,::-1])
155
+ inp = gr.Image(type="pil")
156
+ output = gr.Image(type="pil")
157
+
158
+ examples=[["Examples/Image1.jpg","Image1"],["Examples/Image2.jpg","Image2"]]
159
+
160
+ io=gr.Interface(fn=Custom_detect, inputs=inp, outputs=output, title='Pot Hole Detection With Custom YOLOv7',examples=examples,cache_examples=False)
161
+ io.launch()
162
+