shriarul5273 commited on
Commit
b18a3c4
·
verified ·
1 Parent(s): d57ef88

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +174 -176
app.py CHANGED
@@ -1,177 +1,175 @@
1
- import torch
2
- from models.common import DetectMultiBackend
3
- from utils.general import (check_img_size, cv2,
4
- non_max_suppression, scale_boxes)
5
- from utils.plots import Annotator, colors
6
- import numpy as np
7
- import gradio as gr
8
- import time
9
- data = 'data/coco128.yaml'
10
- import spaces
11
-
12
-
13
- def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleup=True, stride=32):
14
- # Resize and pad image while meeting stride-multiple constraints
15
- shape = im.shape[:2] # current shape [height, width]
16
- if isinstance(new_shape, int):
17
- new_shape = (new_shape, new_shape)
18
-
19
- # Scale ratio (new / old)
20
- r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
21
- if not scaleup: # only scale down, do not scale up (for better val mAP)
22
- r = min(r, 1.0)
23
-
24
- # Compute padding
25
- new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
26
- dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
27
-
28
- if auto: # minimum rectangle
29
- dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
30
-
31
- dw /= 2 # divide padding into 2 sides
32
- dh /= 2
33
-
34
- if shape[::-1] != new_unpad: # resize
35
- im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
36
- top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
37
- left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
38
- im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
39
- return im, r, (dw, dh)
40
-
41
- names = ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
42
- 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
43
- 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
44
- 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
45
- 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
46
- 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
47
- 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
48
- 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
49
- 'hair drier', 'toothbrush']
50
-
51
-
52
-
53
- @spaces.GPU
54
- def detect(im,model,device,iou_threshold=0.45,confidence_threshold=0.25):
55
- im = np.array(im)
56
- imgsz=(640, 640) # inference size (pixels)
57
- data = 'data/coco128.yaml' # data.yaml path
58
- # Load model
59
- stride, names, pt = model.stride, model.names, model.pt
60
- imgsz = check_img_size(imgsz, s=stride) # check image size
61
-
62
- # Run inference
63
- # model.warmup(imgsz=(1)) # warmup
64
-
65
- imgs = im.copy() # for NMS
66
-
67
- image, ratio, dwdh = letterbox(im, auto=False)
68
- print(image.shape)
69
- image = image.transpose((2, 0, 1))
70
- img = torch.from_numpy(image).to(device)
71
- img = img.float() # uint8 to fp16/32
72
- img /= 255.0 # 0 - 255 to 0.0 - 1.0
73
- if img.ndimension() == 3:
74
- img = img.unsqueeze(0)
75
-
76
- # Inference
77
- start = time.time()
78
- pred = model(img, augment=False)
79
- fps_inference = 1/(time.time()-start)
80
- # NMS
81
- pred = non_max_suppression(pred, confidence_threshold, iou_threshold, None, False, max_det=10)
82
-
83
-
84
- for i, det in enumerate(pred): # detections per image
85
- if len(det):
86
- # Rescale boxes from img_size to im0 size
87
- det[:, :4] = scale_boxes(img.shape[2:], det[:, :4], imgs.shape).round()
88
-
89
- annotator = Annotator(imgs, line_width=3, example=str(names))
90
- hide_labels = False
91
- hide_conf = False
92
- # Write results
93
- for *xyxy, conf, cls in reversed(det):
94
- c = int(cls) # integer class
95
- label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
96
- print(xyxy,label)
97
- annotator.box_label(xyxy, label, color=colors(c, True))
98
-
99
- return imgs,fps_inference
100
-
101
-
102
- def inference(img,model_link,iou_threshold,confidence_threshold):
103
- print(model_link)
104
- device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
105
- # Load model
106
- device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
107
- model = DetectMultiBackend('weights/'+str(model_link)+'.pt', device=device, dnn=False, data=data, fp16=False)
108
- return detect(img,model,device,iou_threshold,confidence_threshold)
109
-
110
-
111
- def inference2(video,model_link,iou_threshold,confidence_threshold):
112
- print(model_link)
113
- device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
114
- # Load model
115
- model = DetectMultiBackend('weights/'+str(model_link)+'.pt', device=device, dnn=False, data=data, fp16=False)
116
- frames = cv2.VideoCapture(video)
117
- fps = frames.get(cv2.CAP_PROP_FPS)
118
- image_size = (int(frames.get(cv2.CAP_PROP_FRAME_WIDTH)),int(frames.get(cv2.CAP_PROP_FRAME_HEIGHT)))
119
- finalVideo = cv2.VideoWriter('output.mp4',cv2.VideoWriter_fourcc(*'VP90'), fps, image_size)
120
- fps_video = []
121
- while frames.isOpened():
122
- ret,frame = frames.read()
123
- if not ret:
124
- break
125
- frame,fps = detect(frame,model,device,iou_threshold,confidence_threshold)
126
- fps_video.append(fps)
127
- finalVideo.write(frame)
128
- frames.release()
129
- finalVideo.release()
130
- return 'output.mp4',np.mean(fps_video)
131
-
132
-
133
-
134
- examples_images = ['data/images/bus.jpg',
135
- 'data/images/zidane.jpg',]
136
- examples_videos = ['data/video/input_0.mp4',
137
- 'data/video/input_1.mp4']
138
-
139
- models = ['yolov5s','yolov5n','yolov5m','yolov5l','yolov5x']
140
-
141
- with gr.Blocks() as demo:
142
- gr.Markdown("## YOLOv5 Inference")
143
- with gr.Tab("Image"):
144
- gr.Markdown("## YOLOv5 Inference on Image")
145
- with gr.Row():
146
- image_input = gr.Image(type='pil', label="Input Image", sources="upload")
147
- image_output = gr.Image(type='pil', label="Output Image", sources="upload")
148
- fps_image = gr.Number(value=0,label='FPS')
149
- image_drop = gr.Dropdown(choices=models,value=models[0])
150
- image_iou_threshold = gr.Slider(label="IOU Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.45)
151
- image_conf_threshold = gr.Slider(label="Confidence Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.25)
152
- gr.Examples(examples=examples_images,inputs=image_input,outputs=image_output)
153
- text_button = gr.Button("Detect")
154
- with gr.Tab("Video"):
155
- gr.Markdown("## YOLOv5 Inference on Video")
156
- with gr.Row():
157
- video_input = gr.Video(label="Input Image", sources="upload")
158
- video_output = gr.Video(label="Output Image",format="mp4")
159
- fps_video = gr.Number(value=0,label='FPS')
160
- video_drop = gr.Dropdown(choices=models,value=models[0])
161
- video_iou_threshold = gr.Slider(label="IOU Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.45)
162
- video_conf_threshold = gr.Slider(label="Confidence Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.25)
163
- gr.Examples(examples=examples_videos,inputs=video_input,outputs=video_output)
164
- video_button = gr.Button("Detect")
165
-
166
- with gr.Tab("Webcam Video"):
167
- gr.Markdown("## YOLOv5 Inference on Webcam Video")
168
- gr.Markdown("Coming Soon")
169
-
170
- text_button.click(inference, inputs=[image_input,image_drop,
171
- image_iou_threshold,image_conf_threshold],
172
- outputs=[image_output,fps_image])
173
- video_button.click(inference2, inputs=[video_input,video_drop,
174
- video_iou_threshold,video_conf_threshold],
175
- outputs=[video_output,fps_video])
176
-
177
  demo.launch()
 
1
+ import torch
2
+ from models.common import DetectMultiBackend
3
+ from utils.general import (check_img_size, cv2,
4
+ non_max_suppression, scale_boxes)
5
+ from utils.plots import Annotator, colors
6
+ import numpy as np
7
+ import gradio as gr
8
+ import time
9
+ data = 'data/coco128.yaml'
10
+
11
+
12
+ def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleup=True, stride=32):
13
+ # Resize and pad image while meeting stride-multiple constraints
14
+ shape = im.shape[:2] # current shape [height, width]
15
+ if isinstance(new_shape, int):
16
+ new_shape = (new_shape, new_shape)
17
+
18
+ # Scale ratio (new / old)
19
+ r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
20
+ if not scaleup: # only scale down, do not scale up (for better val mAP)
21
+ r = min(r, 1.0)
22
+
23
+ # Compute padding
24
+ new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
25
+ dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
26
+
27
+ if auto: # minimum rectangle
28
+ dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
29
+
30
+ dw /= 2 # divide padding into 2 sides
31
+ dh /= 2
32
+
33
+ if shape[::-1] != new_unpad: # resize
34
+ im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
35
+ top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
36
+ left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
37
+ im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
38
+ return im, r, (dw, dh)
39
+
40
+ names = ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
41
+ 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
42
+ 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
43
+ 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
44
+ 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
45
+ 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
46
+ 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
47
+ 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
48
+ 'hair drier', 'toothbrush']
49
+
50
+
51
+
52
+ def detect(im,model,device,iou_threshold=0.45,confidence_threshold=0.25):
53
+ im = np.array(im)
54
+ imgsz=(640, 640) # inference size (pixels)
55
+ data = 'data/coco128.yaml' # data.yaml path
56
+ # Load model
57
+ stride, names, pt = model.stride, model.names, model.pt
58
+ imgsz = check_img_size(imgsz, s=stride) # check image size
59
+
60
+ # Run inference
61
+ # model.warmup(imgsz=(1)) # warmup
62
+
63
+ imgs = im.copy() # for NMS
64
+
65
+ image, ratio, dwdh = letterbox(im, auto=False)
66
+ print(image.shape)
67
+ image = image.transpose((2, 0, 1))
68
+ img = torch.from_numpy(image).to(device)
69
+ img = img.float() # uint8 to fp16/32
70
+ img /= 255.0 # 0 - 255 to 0.0 - 1.0
71
+ if img.ndimension() == 3:
72
+ img = img.unsqueeze(0)
73
+
74
+ # Inference
75
+ start = time.time()
76
+ pred = model(img, augment=False)
77
+ fps_inference = 1/(time.time()-start)
78
+ # NMS
79
+ pred = non_max_suppression(pred, confidence_threshold, iou_threshold, None, False, max_det=10)
80
+
81
+
82
+ for i, det in enumerate(pred): # detections per image
83
+ if len(det):
84
+ # Rescale boxes from img_size to im0 size
85
+ det[:, :4] = scale_boxes(img.shape[2:], det[:, :4], imgs.shape).round()
86
+
87
+ annotator = Annotator(imgs, line_width=3, example=str(names))
88
+ hide_labels = False
89
+ hide_conf = False
90
+ # Write results
91
+ for *xyxy, conf, cls in reversed(det):
92
+ c = int(cls) # integer class
93
+ label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
94
+ print(xyxy,label)
95
+ annotator.box_label(xyxy, label, color=colors(c, True))
96
+
97
+ return imgs,fps_inference
98
+
99
+
100
+ def inference(img,model_link,iou_threshold,confidence_threshold):
101
+ print(model_link)
102
+ device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
103
+ # Load model
104
+ device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
105
+ model = DetectMultiBackend('weights/'+str(model_link)+'.pt', device=device, dnn=False, data=data, fp16=False)
106
+ return detect(img,model,device,iou_threshold,confidence_threshold)
107
+
108
+
109
+ def inference2(video,model_link,iou_threshold,confidence_threshold):
110
+ print(model_link)
111
+ device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
112
+ # Load model
113
+ model = DetectMultiBackend('weights/'+str(model_link)+'.pt', device=device, dnn=False, data=data, fp16=False)
114
+ frames = cv2.VideoCapture(video)
115
+ fps = frames.get(cv2.CAP_PROP_FPS)
116
+ image_size = (int(frames.get(cv2.CAP_PROP_FRAME_WIDTH)),int(frames.get(cv2.CAP_PROP_FRAME_HEIGHT)))
117
+ finalVideo = cv2.VideoWriter('output.mp4',cv2.VideoWriter_fourcc(*'VP90'), fps, image_size)
118
+ fps_video = []
119
+ while frames.isOpened():
120
+ ret,frame = frames.read()
121
+ if not ret:
122
+ break
123
+ frame,fps = detect(frame,model,device,iou_threshold,confidence_threshold)
124
+ fps_video.append(fps)
125
+ finalVideo.write(frame)
126
+ frames.release()
127
+ finalVideo.release()
128
+ return 'output.mp4',np.mean(fps_video)
129
+
130
+
131
+
132
+ examples_images = ['data/images/bus.jpg',
133
+ 'data/images/zidane.jpg',]
134
+ examples_videos = ['data/video/input_0.mp4',
135
+ 'data/video/input_1.mp4']
136
+
137
+ models = ['yolov5s','yolov5n','yolov5m','yolov5l','yolov5x']
138
+
139
+ with gr.Blocks() as demo:
140
+ gr.Markdown("## YOLOv5 Inference")
141
+ with gr.Tab("Image"):
142
+ gr.Markdown("## YOLOv5 Inference on Image")
143
+ with gr.Row():
144
+ image_input = gr.Image(type='pil', label="Input Image", sources="upload")
145
+ image_output = gr.Image(type='pil', label="Output Image", sources="upload")
146
+ fps_image = gr.Number(value=0,label='FPS')
147
+ image_drop = gr.Dropdown(choices=models,value=models[0])
148
+ image_iou_threshold = gr.Slider(label="IOU Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.45)
149
+ image_conf_threshold = gr.Slider(label="Confidence Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.25)
150
+ gr.Examples(examples=examples_images,inputs=image_input,outputs=image_output)
151
+ text_button = gr.Button("Detect")
152
+ with gr.Tab("Video"):
153
+ gr.Markdown("## YOLOv5 Inference on Video")
154
+ with gr.Row():
155
+ video_input = gr.Video(label="Input Image", sources="upload")
156
+ video_output = gr.Video(label="Output Image",format="mp4")
157
+ fps_video = gr.Number(value=0,label='FPS')
158
+ video_drop = gr.Dropdown(choices=models,value=models[0])
159
+ video_iou_threshold = gr.Slider(label="IOU Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.45)
160
+ video_conf_threshold = gr.Slider(label="Confidence Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.25)
161
+ gr.Examples(examples=examples_videos,inputs=video_input,outputs=video_output)
162
+ video_button = gr.Button("Detect")
163
+
164
+ with gr.Tab("Webcam Video"):
165
+ gr.Markdown("## YOLOv5 Inference on Webcam Video")
166
+ gr.Markdown("Coming Soon")
167
+
168
+ text_button.click(inference, inputs=[image_input,image_drop,
169
+ image_iou_threshold,image_conf_threshold],
170
+ outputs=[image_output,fps_image])
171
+ video_button.click(inference2, inputs=[video_input,video_drop,
172
+ video_iou_threshold,video_conf_threshold],
173
+ outputs=[video_output,fps_video])
174
+
 
 
175
  demo.launch()