-
Notifications
You must be signed in to change notification settings - Fork 17
/
main.py
223 lines (173 loc) · 5.4 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
"""
utf-8 python3
Time : 20/11/12
Author : Sourav R S
File : main.py
"""
""" Necessary imports """
import cv2
import argparse
from tools.utils import *
from tools.torch_utils import *
from tools.darknet2pytorch import Darknet
# from tools.VideoCapture import VideoCapture
def str2int(source):
"""Converts the source obtained from arguments
to int handles both videosources and webcam
indexes"""
try:
return int(source)
except ValueError:
return source
def run_inference(cfgfile, weightfile, namesfile, source, output, conf, nms, save_net):
model = Darknet(cfgfile)
model.print_network()
""" Save network if you want to use it """
if save_net != " ":
model.save_weights(outfile=save_net)
""" Throws error if could not load weight file """
try:
model.load_weights(weightfile)
except Exception:
print("Could not load Weights")
""" Check if cuda is available """
cuda = torch.cuda.is_available()
""" If GPU is available load the model onto the GPU """
if cuda:
print("CUDA found running on GPU")
model.cuda()
print("CUDA not found running on CPU")
""" Switching model to eval mode and
setting torch.no_grad """
model.eval()
with torch.no_grad():
""" Grab the frame from source """
source = str2int(source)
cap = cv2.VideoCapture(source)
"""Get height width and frame rate of input video """
width = int(cap.get(3))
height = int(cap.get(4))
frame_rate = int(cap.get(cv2.CAP_PROP_FPS))
""" Load the labels from the .names file """
class_names = load_class_names(namesfile)
""" Video writer """
if output != " ":
out = cv2.VideoWriter(
output,
cv2.VideoWriter_fourcc("X", "2", "6", "4"),
frame_rate,
(width, height),
)
while True:
ret, img = cap.read()
""" Checked to see frame received successfully """
if not ret:
exit(0)
try:
"""Resize the image to those specified
in the configuration file"""
img_resized = cv2.resize(img, (model.width, model.height))
img_rgb = cv2.cvtColor(img_resized, cv2.COLOR_BGR2RGB)
start = time.time()
boxes = do_detect(model, img_rgb, conf, nms, cuda)
print("predicted in %f seconds." % (time.time() - start))
""" Returns the annotated images """
antd_img = plot_boxes_cv2(
img, boxes[0], savename=None, class_names=class_names
)
"""Calculate the framerate for the inference loop """
fps = int(1 / (time.time() - start))
print(f"FPS: {fps}")
except Exception:
pass
""" Write frame into output.mp4 file """
if output != " ":
out.write(antd_img)
""" Implicitly create a named window """
cv2.namedWindow("Inference", cv2.WINDOW_NORMAL)
""" Show the frame """
cv2.imshow("Inference", antd_img)
key = cv2.waitKey(1)
""" If the 'q' key is pressed break
out of the loop """
if key & 0xFF == ord("q"):
break
""" Release the frame and writer"""
cap.release()
if output != " ":
out.release()
cv2.destroyAllWindows()
def arguments():
""" Arguments for running infernce """
parser = argparse.ArgumentParser("Arguments for running inference.")
parser.add_argument(
"-cfgfile",
type=str,
default="./cfg/yolov4.cfg",
help="Path to the configuration file",
dest="cfgfile",
)
parser.add_argument(
"-weightfile",
type=str,
default="./weights/yolov4.weights",
help="Path to the weights file",
dest="weightfile",
)
parser.add_argument(
"-namesfile",
type=str,
default="./cfg/classes.names",
help="Path to the classes name file",
dest="namesfile",
)
parser.add_argument(
"-source",
type=str,
default=0,
help="Source for webcam default 0 for the built in webcam",
dest="source",
)
parser.add_argument(
"-output",
type=str,
default=" ",
help="Name of the output result video",
dest="output",
)
parser.add_argument(
"-conf",
type=float,
default=0.4,
help="Confidence threshold for inference",
dest="conf_thresh",
)
parser.add_argument(
"-nms",
type=float,
default=0.6,
help="Non maximum supression threshold",
dest="nms_thresh",
)
parser.add_argument(
"-save_weight",
type=str,
default=" ",
help="Save weight to pytorch format output weight file name",
dest="save_net",
)
args = parser.parse_args()
return args
if __name__ == "__main__":
args = arguments()
""" Start the inference function """
run_inference(
args.cfgfile,
args.weightfile,
args.namesfile,
args.source,
args.output,
args.conf_thresh,
args.nms_thresh,
args.save_net,
)