owaiskha9654 commited on
Commit
51ecb43
·
2 Parent(s): ef3fd6e ec1ad04

Merge branch 'main' of https://huggingface.co/spaces/owaiskha9654/Custom_Yolov7_Car_Person

Browse files
Files changed (2) hide show
  1. app.py +58 -82
  2. requirements.txt +31 -8
app.py CHANGED
@@ -1,34 +1,31 @@
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
- os.system("wget https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-e6e.pt")
6
- os.system("wget https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-e6.pt")
7
-
8
- import argparse
9
- import time
10
- from pathlib import Path
11
-
12
  import cv2
 
13
  import torch
14
- import torch.backends.cudnn as cudnn
 
 
15
  from numpy import random
16
-
 
17
  from models.experimental import attempt_load
 
18
  from utils.datasets import LoadStreams, LoadImages
19
  from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \
20
  scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path
21
  from utils.plots import plot_one_box
22
  from utils.torch_utils import select_device, load_classifier, time_synchronized, TracedModel
23
- from PIL import Image
24
-
25
-
26
-
27
 
 
28
  def detect_Custom(img,model):
 
 
29
  parser = argparse.ArgumentParser()
30
  parser.add_argument('--weights', nargs='+', type=str, default=model+".pt", help='model.pt path(s)')
31
- parser.add_argument('--source', type=str, default='Inference/', help='source') # file/folder, 0 for webcam
32
  parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
33
  parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
34
  parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
@@ -48,57 +45,42 @@ def detect_Custom(img,model):
48
  opt = parser.parse_args()
49
  img.save("Inference/test.jpg")
50
  source, weights, view_img, save_txt, imgsz, trace = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size, opt.trace
51
- save_img = True # save inference images
52
  webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
53
  ('rtsp://', 'rtmp://', 'http://', 'https://'))
54
-
55
- # Directories
56
- save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)) # increment run
57
- (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
58
-
59
- # Initialize
60
  set_logging()
61
  device = select_device(opt.device)
62
- half = device.type != 'cpu' # half precision only supported on CUDA
63
-
64
- # Load model
65
- model = attempt_load(weights, map_location=device) # load FP32 model
66
- stride = int(model.stride.max()) # model stride
67
- imgsz = check_img_size(imgsz, s=stride) # check img_size
68
-
69
  if trace:
70
  model = TracedModel(model, device, opt.img_size)
71
-
72
  if half:
73
- model.half() # to FP16
74
-
75
- # Second-stage classifier
76
  classify = False
77
  if classify:
78
  modelc = load_classifier(name='resnet101', n=2) # initialize
79
  modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()
80
-
81
- # Set Dataloader
82
  vid_path, vid_writer = None, None
83
  if webcam:
84
  view_img = check_imshow()
85
- cudnn.benchmark = True # set True to speed up constant image size inference
86
  dataset = LoadStreams(source, img_size=imgsz, stride=stride)
87
  else:
88
  dataset = LoadImages(source, img_size=imgsz, stride=stride)
89
-
90
- # Get names and colors
91
  names = model.module.names if hasattr(model, 'module') else model.names
92
  colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]
93
-
94
- # Run inference
95
  if device.type != 'cpu':
96
- model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
97
  t0 = time.time()
98
  for path, img, im0s, vid_cap in dataset:
99
  img = torch.from_numpy(img).to(device)
100
- img = img.half() if half else img.float() # uint8 to fp16/32
101
- img /= 255.0 # 0 - 255 to 0.0 - 1.0
102
  if img.ndimension() == 3:
103
  img = img.unsqueeze(0)
104
 
@@ -106,69 +88,62 @@ def detect_Custom(img,model):
106
  t1 = time_synchronized()
107
  pred = model(img, augment=opt.augment)[0]
108
 
109
- # Apply NMS
110
  pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
111
  t2 = time_synchronized()
112
-
 
113
  # Apply Classifier
114
  if classify:
115
  pred = apply_classifier(pred, modelc, img, im0s)
116
-
117
- # Process detections
118
- for i, det in enumerate(pred): # detections per image
119
- if webcam: # batch_size >= 1
120
  p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
121
  else:
122
  p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)
123
 
124
- p = Path(p) # to Path
125
- save_path = str(save_dir / p.name) # img.jpg
126
  txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
127
- s += '%gx%g ' % img.shape[2:] # print string
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
 
133
- # Print results
134
  for c in det[:, -1].unique():
135
- n = (det[:, -1] == c).sum() # detections per class
136
- s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
137
 
138
- # Write results
139
  for *xyxy, conf, cls in reversed(det):
140
- if save_txt: # Write to file
141
- xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
142
- line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format
143
  with open(txt_path + '.txt', 'a') as f:
144
  f.write(('%g ' * len(line)).rstrip() % line + '\n')
145
 
146
- if save_img or view_img: # Add bbox to image
147
  label = f'{names[int(cls)]} {conf:.2f}'
148
  plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
149
-
150
- # Print time (inference + NMS)
151
- #print(f'{s}Done. ({t2 - t1:.3f}s)')
152
-
153
- # Stream results
154
  if view_img:
155
  cv2.imshow(str(p), im0)
156
- cv2.waitKey(1) # 1 millisecond
157
 
158
- # Save results (image with detections)
159
  if save_img:
160
  if dataset.mode == 'image':
161
  cv2.imwrite(save_path, im0)
162
- else: # 'video' or 'stream'
163
- if vid_path != save_path: # new video
164
  vid_path = save_path
165
  if isinstance(vid_writer, cv2.VideoWriter):
166
- vid_writer.release() # release previous video writer
167
- if vid_cap: # video
168
  fps = vid_cap.get(cv2.CAP_PROP_FPS)
169
  w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
170
  h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
171
- else: # stream
172
  fps, w, h = 30, im0.shape[1], im0.shape[0]
173
  save_path += '.mp4'
174
  vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
@@ -176,7 +151,6 @@ def detect_Custom(img,model):
176
 
177
  if save_txt or save_img:
178
  s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
179
- #print(f"Results saved to {save_dir}{s}")
180
 
181
  print(f'Done. ({time.time() - t0:.3f}s)')
182
 
@@ -184,10 +158,10 @@ def detect_Custom(img,model):
184
 
185
 
186
 
187
- description="Custom Training Performed on Kaggle <a href='https://www.kaggle.com/code/owaiskhan9654/training-yolov7-on-kaggle-on-custom-dataset/notebook' style='text-decoration: underline' target='_blank'>Link</a> <br> Trainable bag-of-freebies sets new state-of-the-art for real-time object detectors <br> Also Please use <b>Images with .jpeg</b> because Yolo V7 Model is trained on GPU and while inferencing default CPU has been implemented"
188
 
189
- text1 = (
190
- "<center> Custom Model Trained by: Owais Ahmad Data Scientist at <b> Thoucentric </b> <a href=\"https://www.linkedin.com/in/owaiskhan9654/\">Visit Profile</a> <br></center>"
191
 
192
  "<center> Model Trained Kaggle Kernel <a href=\"https://www.kaggle.com/code/owaiskhan9654/training-yolov7-on-kaggle-on-custom-dataset/notebook\">Link</a> <br></center>"
193
 
@@ -196,6 +170,8 @@ text1 = (
196
  "<center> HuggingFace🤗 Model Deployed Repository <a href=\"https://huggingface.co/owaiskha9654/Yolov7_Custom_Object_Detection\">Link</a> <br></center>"
197
  )
198
 
 
 
 
199
 
200
- gr.Interface(detect_Custom,[gr.Image(type="pil"),gr.Dropdown(default="Yolo_v7_Custom_trained_By_Owais",\
201
- choices=["best","yolov7","yolov7-e6"])], gr.Image(type="pil"),title="Yolov7 Custom Trained by <a href='https://www.linkedin.com/in/owaiskhan9654/' style='text-decoration: underline' target='_blank'>Owais Ahmad</a> ",examples=[["Image1.jpeg",\ "Yolo_v7_Custom_trained_By_Owais"],["Image2.jpeg", "Yolo_v7_Custom_trained_By_Owais"],["Image3.jpeg", "Yolo_v7_Custom_trained_By_Owais",],["Image4.jpeg", "Yolo_v7_Custom_trained_By_Owais"],["Image5.jpeg", "Yolo_v7_Custom_trained_By_Owais"],["Image6.jpeg", "Yolo_v7_Custom_trained_By_Owais"],["horses.jpeg", "yolov7"]],cache_examples=False).launch()
 
 
1
  import os
 
 
 
 
 
 
 
 
 
2
  import cv2
3
+ import time
4
  import torch
5
+ import argparse
6
+ import gradio as gr
7
+ from PIL import Image
8
  from numpy import random
9
+ from pathlib import Path
10
+ import torch.backends.cudnn as cudnn
11
  from models.experimental import attempt_load
12
+
13
  from utils.datasets import LoadStreams, LoadImages
14
  from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \
15
  scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path
16
  from utils.plots import plot_one_box
17
  from utils.torch_utils import select_device, load_classifier, time_synchronized, TracedModel
18
+ os.system("wget https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7.pt")
19
+ os.system("wget https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-e6e.pt")
20
+ os.system("wget https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-e6.pt")
 
21
 
22
+
23
  def detect_Custom(img,model):
24
+ if model =='Yolo_v7_Custom_trained_By_Owais':
25
+ model='best' # Naming Convention for yolov7 See output file of https://www.kaggle.com/code/owaiskhan9654/training-yolov7-on-kaggle-on-custom-dataset/data
26
  parser = argparse.ArgumentParser()
27
  parser.add_argument('--weights', nargs='+', type=str, default=model+".pt", help='model.pt path(s)')
28
+ parser.add_argument('--source', type=str, default='Inference/', help='source')
29
  parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
30
  parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
31
  parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
 
45
  opt = parser.parse_args()
46
  img.save("Inference/test.jpg")
47
  source, weights, view_img, save_txt, imgsz, trace = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size, opt.trace
48
+ save_img = True
49
  webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
50
  ('rtsp://', 'rtmp://', 'http://', 'https://'))
51
+ save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok))
52
+ (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)
 
 
 
 
53
  set_logging()
54
  device = select_device(opt.device)
55
+ half = device.type != 'cpu'
56
+ model = attempt_load(weights, map_location=device)
57
+ stride = int(model.stride.max())
58
+ imgsz = check_img_size(imgsz, s=stride)
 
 
 
59
  if trace:
60
  model = TracedModel(model, device, opt.img_size)
 
61
  if half:
62
+ model.half()
63
+
 
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
  vid_path, vid_writer = None, None
69
  if webcam:
70
  view_img = check_imshow()
71
+ cudnn.benchmark = True
72
  dataset = LoadStreams(source, img_size=imgsz, stride=stride)
73
  else:
74
  dataset = LoadImages(source, img_size=imgsz, stride=stride)
 
 
75
  names = model.module.names if hasattr(model, 'module') else model.names
76
  colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]
 
 
77
  if device.type != 'cpu':
78
+ model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters())))
79
  t0 = time.time()
80
  for path, img, im0s, vid_cap in dataset:
81
  img = torch.from_numpy(img).to(device)
82
+ img = img.half() if half else img.float()
83
+ img /= 255.0
84
  if img.ndimension() == 3:
85
  img = img.unsqueeze(0)
86
 
 
88
  t1 = time_synchronized()
89
  pred = model(img, augment=opt.augment)[0]
90
 
91
+
92
  pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
93
  t2 = time_synchronized()
94
+
95
+
96
  # Apply Classifier
97
  if classify:
98
  pred = apply_classifier(pred, modelc, img, im0s)
99
+
100
+ for i, det in enumerate(pred):
101
+ if webcam:
 
102
  p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
103
  else:
104
  p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)
105
 
106
+ p = Path(p)
107
+ save_path = str(save_dir / p.name)
108
  txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
109
+ s += '%gx%g ' % img.shape[2:]
110
+ gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]
111
  if len(det):
 
112
  det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
113
 
114
+
115
  for c in det[:, -1].unique():
116
+ n = (det[:, -1] == c).sum()
117
+ s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "
118
 
119
+
120
  for *xyxy, conf, cls in reversed(det):
121
+ if save_txt:
122
+ xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()
123
+ line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh)
124
  with open(txt_path + '.txt', 'a') as f:
125
  f.write(('%g ' * len(line)).rstrip() % line + '\n')
126
 
127
+ if save_img or view_img:
128
  label = f'{names[int(cls)]} {conf:.2f}'
129
  plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
 
 
 
 
 
130
  if view_img:
131
  cv2.imshow(str(p), im0)
132
+ cv2.waitKey(1)
133
 
 
134
  if save_img:
135
  if dataset.mode == 'image':
136
  cv2.imwrite(save_path, im0)
137
+ else:
138
+ if vid_path != save_path:
139
  vid_path = save_path
140
  if isinstance(vid_writer, cv2.VideoWriter):
141
+ vid_writer.release()
142
+ if vid_cap:
143
  fps = vid_cap.get(cv2.CAP_PROP_FPS)
144
  w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
145
  h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
146
+ else:
147
  fps, w, h = 30, im0.shape[1], im0.shape[0]
148
  save_path += '.mp4'
149
  vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
 
151
 
152
  if save_txt or save_img:
153
  s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
 
154
 
155
  print(f'Done. ({time.time() - t0:.3f}s)')
156
 
 
158
 
159
 
160
 
161
+ Custom_description="<center>Custom Training Performed on Kaggle <a href='https://www.kaggle.com/code/owaiskhan9654/training-yolov7-on-kaggle-on-custom-dataset/notebook' style='text-decoration: underline' target='_blank'>Link</a> </center><br> <center>Trainable bag-of-freebies sets new state-of-the-art for real-time object detectors </center> <br> <b>1st</b> class is for Person Detected<br><b>2nd</b> class is for Car Detected"
162
 
163
+ Footer = (
164
+ "<center>Model Trained by: Owais Ahmad Data Scientist at <b> Thoucentric </b> <a href=\"https://www.linkedin.com/in/owaiskhan9654/\">Visit Profile</a> <br></center>"
165
 
166
  "<center> Model Trained Kaggle Kernel <a href=\"https://www.kaggle.com/code/owaiskhan9654/training-yolov7-on-kaggle-on-custom-dataset/notebook\">Link</a> <br></center>"
167
 
 
170
  "<center> HuggingFace🤗 Model Deployed Repository <a href=\"https://huggingface.co/owaiskha9654/Yolov7_Custom_Object_Detection\">Link</a> <br></center>"
171
  )
172
 
173
+ examples1=[["Image1.jpeg", "Yolo_v7_Custom_trained_By_Owais"],["Image2.jpeg", "Yolo_v7_Custom_trained_By_Owais"],["Image3.jpeg", "Yolo_v7_Custom_trained_By_Owais",],["Image4.jpeg", "Yolo_v7_Custom_trained_By_Owais"],["Image5.jpeg", "Yolo_v7_Custom_trained_By_Owais"],["Image6.jpeg", "Yolo_v7_Custom_trained_By_Owais"],["horses.jpeg", "yolov7"],["horses.jpeg", "yolov7-e6"]]
174
+
175
+ Top_Title="<center>Yolov7 🚀 Custom Trained by <a href='https://www.linkedin.com/in/owaiskhan9654/' style='text-decoration: underline' target='_blank'>Owais Ahmad </center></a>🚗Car and 👦Person Detection"
176
 
177
+ gr.Interface(detect_Custom,[gr.Image(type="pil"),gr.Dropdown(default="Yolo_v7_Custom_trained_By_Owais",choices=["Yolo_v7_Custom_trained_By_Owais","yolov7","yolov7-e6"])],gr.Image(type="pil"),title=Top_Title,examples=examples1,description=Custom_description,article=Footer,cache_examples=False).launch()
 
requirements.txt CHANGED
@@ -1,18 +1,41 @@
 
 
 
 
 
1
  matplotlib>=3.2.2
2
- gradio==3.1.4
3
  numpy>=1.18.5
4
  opencv-python>=4.1.1
5
  Pillow>=7.1.2
6
  PyYAML>=5.3.1
7
  requests>=2.23.0
8
- scipy>=1.4.1
9
- torch>=1.7.0
10
- torchvision>=0.8.1
11
  tqdm>=4.41.0
12
- protobuf<=3.20.1
 
 
13
  tensorboard>=2.4.1
 
 
 
14
  pandas>=1.1.4
15
  seaborn>=0.11.0
16
- ipython
17
- psutil
18
- thop
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #Yolov7 WongKinYiu Requirements
2
+
3
+ # Usage: pip install -r requirements.txt
4
+
5
+ # Base ----------------------------------------
6
  matplotlib>=3.2.2
 
7
  numpy>=1.18.5
8
  opencv-python>=4.1.1
9
  Pillow>=7.1.2
10
  PyYAML>=5.3.1
11
  requests>=2.23.0
12
+ scipy>=1.4.1
13
+ torch>=1.7.0,!=1.12.0
14
+ torchvision>=0.8.1,!=0.13.0
15
  tqdm>=4.41.0
16
+ protobuf<4.21.3
17
+
18
+ # Logging -------------------------------------
19
  tensorboard>=2.4.1
20
+ # wandb
21
+
22
+ # Plotting ------------------------------------
23
  pandas>=1.1.4
24
  seaborn>=0.11.0
25
+
26
+ # Export --------------------------------------
27
+ # coremltools>=4.1 # CoreML export
28
+ # onnx>=1.9.0 # ONNX export
29
+ # onnx-simplifier>=0.3.6 # ONNX simplifier
30
+ # scikit-learn==0.19.2 # CoreML quantization
31
+ # tensorflow>=2.4.1 # TFLite export
32
+ # tensorflowjs>=3.9.0 # TF.js export
33
+ # openvino-dev # OpenVINO export
34
+
35
+ # Extras --------------------------------------
36
+ ipython # interactive notebook
37
+ psutil # system utilization
38
+ thop # FLOPs computation
39
+ # albumentations>=1.0.3
40
+ # pycocotools>=2.0 # COCO mAP
41
+ # roboflow