shriarul5273 commited on
Commit
78c9258
·
verified ·
1 Parent(s): 624f589

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +175 -175
  2. requirements.txt +12 -12
app.py CHANGED
@@ -1,176 +1,176 @@
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
-
53
- def detect(im,model,device,iou_threshold=0.45,confidence_threshold=0.25):
54
- im = np.array(im)
55
- imgsz=(640, 640) # inference size (pixels)
56
- data = 'data/coco128.yaml' # data.yaml path
57
- # Load model
58
- stride, names, pt = model.stride, model.names, model.pt
59
- imgsz = check_img_size(imgsz, s=stride) # check image size
60
-
61
- # Run inference
62
- # model.warmup(imgsz=(1)) # warmup
63
-
64
- imgs = im.copy() # for NMS
65
-
66
- image, ratio, dwdh = letterbox(im, auto=False)
67
- print(image.shape)
68
- image = image.transpose((2, 0, 1))
69
- img = torch.from_numpy(image).to(device)
70
- img = img.float() # uint8 to fp16/32
71
- img /= 255.0 # 0 - 255 to 0.0 - 1.0
72
- if img.ndimension() == 3:
73
- img = img.unsqueeze(0)
74
-
75
- # Inference
76
- start = time.time()
77
- pred = model(img, augment=False)
78
- fps_inference = 1/(time.time()-start)
79
- # NMS
80
- pred = non_max_suppression(pred, confidence_threshold, iou_threshold, None, False, max_det=10)
81
-
82
-
83
- for i, det in enumerate(pred): # detections per image
84
- if len(det):
85
- # Rescale boxes from img_size to im0 size
86
- det[:, :4] = scale_boxes(img.shape[2:], det[:, :4], imgs.shape).round()
87
-
88
- annotator = Annotator(imgs, line_width=3, example=str(names))
89
- hide_labels = False
90
- hide_conf = False
91
- # Write results
92
- for *xyxy, conf, cls in reversed(det):
93
- c = int(cls) # integer class
94
- label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
95
- print(xyxy,label)
96
- annotator.box_label(xyxy, label, color=colors(c, True))
97
-
98
- return imgs,fps_inference
99
-
100
-
101
- def inference(img,model_link,iou_threshold,confidence_threshold):
102
- print(model_link)
103
- device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
104
- # Load model
105
- device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
106
- model = DetectMultiBackend('weights/'+str(model_link)+'.pt', device=device, dnn=False, data=data, fp16=False)
107
- return detect(img,model,device,iou_threshold,confidence_threshold)
108
-
109
-
110
- def inference2(video,model_link,iou_threshold,confidence_threshold):
111
- print(model_link)
112
- device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
113
- # Load model
114
- model = DetectMultiBackend('weights/'+str(model_link)+'.pt', device=device, dnn=False, data=data, fp16=False)
115
- frames = cv2.VideoCapture(video)
116
- fps = frames.get(cv2.CAP_PROP_FPS)
117
- image_size = (int(frames.get(cv2.CAP_PROP_FRAME_WIDTH)),int(frames.get(cv2.CAP_PROP_FRAME_HEIGHT)))
118
- finalVideo = cv2.VideoWriter('output.mp4',cv2.VideoWriter_fourcc(*'VP90'), fps, image_size)
119
- fps_video = []
120
- while frames.isOpened():
121
- ret,frame = frames.read()
122
- if not ret:
123
- break
124
- frame,fps = detect(frame,model,device,iou_threshold,confidence_threshold)
125
- fps_video.append(fps)
126
- finalVideo.write(frame)
127
- frames.release()
128
- finalVideo.release()
129
- return 'output.mp4',np.mean(fps_video)
130
-
131
-
132
-
133
- examples_images = ['data/images/bus.jpg',
134
- 'data/images/zidane.jpg',]
135
- examples_videos = ['data/video/input_0.mp4',
136
- 'data/video/input_1.mp4']
137
-
138
- models = ['yolov5s','yolov5n','yolov5m','yolov5l','yolov5x']
139
-
140
- with gr.Blocks() as demo:
141
- gr.Markdown("## YOLOv5 Inference")
142
- with gr.Tab("Image"):
143
- gr.Markdown("## YOLOv5 Inference on Image")
144
- with gr.Row():
145
- image_input = gr.Image(type='pil', label="Input Image", source="upload")
146
- image_output = gr.Image(type='pil', label="Output Image", source="upload")
147
- fps_image = gr.Number(value=0,label='FPS')
148
- image_drop = gr.Dropdown(choices=models,value=models[0])
149
- image_iou_threshold = gr.Slider(label="IOU Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.45)
150
- image_conf_threshold = gr.Slider(label="Confidence Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.25)
151
- gr.Examples(examples=examples_images,inputs=image_input,outputs=image_output)
152
- text_button = gr.Button("Detect")
153
- with gr.Tab("Video"):
154
- gr.Markdown("## YOLOv5 Inference on Video")
155
- with gr.Row():
156
- video_input = gr.Video(type='pil', label="Input Image", source="upload")
157
- video_output = gr.Video(type="pil", label="Output Image",format="mp4")
158
- fps_video = gr.Number(value=0,label='FPS')
159
- video_drop = gr.Dropdown(choices=models,value=models[0])
160
- video_iou_threshold = gr.Slider(label="IOU Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.45)
161
- video_conf_threshold = gr.Slider(label="Confidence Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.25)
162
- gr.Examples(examples=examples_videos,inputs=video_input,outputs=video_output)
163
- video_button = gr.Button("Detect")
164
-
165
- with gr.Tab("Webcam Video"):
166
- gr.Markdown("## YOLOv5 Inference on Webcam Video")
167
- gr.Markdown("Coming Soon")
168
-
169
- text_button.click(inference, inputs=[image_input,image_drop,
170
- image_iou_threshold,image_conf_threshold],
171
- outputs=[image_output,fps_image])
172
- video_button.click(inference2, inputs=[video_input,video_drop,
173
- video_iou_threshold,video_conf_threshold],
174
- outputs=[video_output,fps_video])
175
-
176
  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
+
53
+ def detect(im,model,device,iou_threshold=0.45,confidence_threshold=0.25):
54
+ im = np.array(im)
55
+ imgsz=(640, 640) # inference size (pixels)
56
+ data = 'data/coco128.yaml' # data.yaml path
57
+ # Load model
58
+ stride, names, pt = model.stride, model.names, model.pt
59
+ imgsz = check_img_size(imgsz, s=stride) # check image size
60
+
61
+ # Run inference
62
+ # model.warmup(imgsz=(1)) # warmup
63
+
64
+ imgs = im.copy() # for NMS
65
+
66
+ image, ratio, dwdh = letterbox(im, auto=False)
67
+ print(image.shape)
68
+ image = image.transpose((2, 0, 1))
69
+ img = torch.from_numpy(image).to(device)
70
+ img = img.float() # uint8 to fp16/32
71
+ img /= 255.0 # 0 - 255 to 0.0 - 1.0
72
+ if img.ndimension() == 3:
73
+ img = img.unsqueeze(0)
74
+
75
+ # Inference
76
+ start = time.time()
77
+ pred = model(img, augment=False)
78
+ fps_inference = 1/(time.time()-start)
79
+ # NMS
80
+ pred = non_max_suppression(pred, confidence_threshold, iou_threshold, None, False, max_det=10)
81
+
82
+
83
+ for i, det in enumerate(pred): # detections per image
84
+ if len(det):
85
+ # Rescale boxes from img_size to im0 size
86
+ det[:, :4] = scale_boxes(img.shape[2:], det[:, :4], imgs.shape).round()
87
+
88
+ annotator = Annotator(imgs, line_width=3, example=str(names))
89
+ hide_labels = False
90
+ hide_conf = False
91
+ # Write results
92
+ for *xyxy, conf, cls in reversed(det):
93
+ c = int(cls) # integer class
94
+ label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
95
+ print(xyxy,label)
96
+ annotator.box_label(xyxy, label, color=colors(c, True))
97
+
98
+ return imgs,fps_inference
99
+
100
+
101
+ def inference(img,model_link,iou_threshold,confidence_threshold):
102
+ print(model_link)
103
+ device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
104
+ # Load model
105
+ device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
106
+ model = DetectMultiBackend('weights/'+str(model_link)+'.pt', device=device, dnn=False, data=data, fp16=False)
107
+ return detect(img,model,device,iou_threshold,confidence_threshold)
108
+
109
+
110
+ def inference2(video,model_link,iou_threshold,confidence_threshold):
111
+ print(model_link)
112
+ device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
113
+ # Load model
114
+ model = DetectMultiBackend('weights/'+str(model_link)+'.pt', device=device, dnn=False, data=data, fp16=False)
115
+ frames = cv2.VideoCapture(video)
116
+ fps = frames.get(cv2.CAP_PROP_FPS)
117
+ image_size = (int(frames.get(cv2.CAP_PROP_FRAME_WIDTH)),int(frames.get(cv2.CAP_PROP_FRAME_HEIGHT)))
118
+ finalVideo = cv2.VideoWriter('output.mp4',cv2.VideoWriter_fourcc(*'VP90'), fps, image_size)
119
+ fps_video = []
120
+ while frames.isOpened():
121
+ ret,frame = frames.read()
122
+ if not ret:
123
+ break
124
+ frame,fps = detect(frame,model,device,iou_threshold,confidence_threshold)
125
+ fps_video.append(fps)
126
+ finalVideo.write(frame)
127
+ frames.release()
128
+ finalVideo.release()
129
+ return 'output.mp4',np.mean(fps_video)
130
+
131
+
132
+
133
+ examples_images = ['data/images/bus.jpg',
134
+ 'data/images/zidane.jpg',]
135
+ examples_videos = ['data/video/input_0.mp4',
136
+ 'data/video/input_1.mp4']
137
+
138
+ models = ['yolov5s','yolov5n','yolov5m','yolov5l','yolov5x']
139
+
140
+ with gr.Blocks() as demo:
141
+ gr.Markdown("## YOLOv5 Inference")
142
+ with gr.Tab("Image"):
143
+ gr.Markdown("## YOLOv5 Inference on Image")
144
+ with gr.Row():
145
+ image_input = gr.Image(type='pil', label="Input Image", sources="upload")
146
+ image_output = gr.Image(type='pil', label="Output Image", sources="upload")
147
+ fps_image = gr.Number(value=0,label='FPS')
148
+ image_drop = gr.Dropdown(choices=models,value=models[0])
149
+ image_iou_threshold = gr.Slider(label="IOU Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.45)
150
+ image_conf_threshold = gr.Slider(label="Confidence Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.25)
151
+ gr.Examples(examples=examples_images,inputs=image_input,outputs=image_output)
152
+ text_button = gr.Button("Detect")
153
+ with gr.Tab("Video"):
154
+ gr.Markdown("## YOLOv5 Inference on Video")
155
+ with gr.Row():
156
+ video_input = gr.Video(label="Input Image", sources="upload")
157
+ video_output = gr.Video(label="Output Image",format="mp4")
158
+ fps_video = gr.Number(value=0,label='FPS')
159
+ video_drop = gr.Dropdown(choices=models,value=models[0])
160
+ video_iou_threshold = gr.Slider(label="IOU Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.45)
161
+ video_conf_threshold = gr.Slider(label="Confidence Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.25)
162
+ gr.Examples(examples=examples_videos,inputs=video_input,outputs=video_output)
163
+ video_button = gr.Button("Detect")
164
+
165
+ with gr.Tab("Webcam Video"):
166
+ gr.Markdown("## YOLOv5 Inference on Webcam Video")
167
+ gr.Markdown("Coming Soon")
168
+
169
+ text_button.click(inference, inputs=[image_input,image_drop,
170
+ image_iou_threshold,image_conf_threshold],
171
+ outputs=[image_output,fps_image])
172
+ video_button.click(inference2, inputs=[video_input,video_drop,
173
+ video_iou_threshold,video_conf_threshold],
174
+ outputs=[video_output,fps_video])
175
+
176
  demo.launch()
requirements.txt CHANGED
@@ -1,12 +1,12 @@
1
- ipython
2
- numpy>=1.18.5
3
- opencv-python>=4.1.1
4
- Pillow>=7.1.2
5
- scipy>=1.4.1
6
- torch>=1.7.0
7
- torchvision>=0.8.1
8
- tqdm>=4.64.0
9
- seaborn>=0.11.0
10
- gradio==3.44.1
11
- psutil
12
- pandas
 
1
+ ipython==8.30.0
2
+ numpy==1.24.3
3
+ opencv-python==4.10.0
4
+ Pillow==11.0.0
5
+ scipy==1.14.1
6
+ torch==2.3.0
7
+ torchvision==0.18.0
8
+ tqdm==4.67.1
9
+ seaborn==0.13.2
10
+ gradio==5.9.1
11
+ psutil==5.9.8
12
+ pandas==2.2.3