-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert_weights.py
More file actions
64 lines (55 loc) · 2.35 KB
/
Copy pathconvert_weights.py
File metadata and controls
64 lines (55 loc) · 2.35 KB
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
# convert_weights.py
import numpy as np
from yolov3 import YOLOv3Net
from yolov3 import parse_cfg
def load_weights(model, cfgfile, weightfile):
# Open the weights file
fp = open(weightfile, "rb")
# Skip 5 header values
np.fromfile(fp, dtype=np.int32, count=5)
# The rest of the values are the weights
blocks = parse_cfg(cfgfile)
for i, block in enumerate(blocks[1:]):
if (block["type"] == "convolutional"):
conv_layer = model.get_layer('conv_' + str(i))
print("layer: ", i + 1, conv_layer)
filters = conv_layer.filters
k_size = conv_layer.kernel_size[0]
in_dim = conv_layer.input_shape[-1]
if "batch_normalize" in block:
norm_layer = model.get_layer('bnorm_' + str(i))
print("layer: ", i + 1, norm_layer)
size = np.prod(norm_layer.get_weights()[0].shape)
bn_weights = np.fromfile(fp, dtype=np.float32, count=4 * filters)
# tf [gamma, beta, mean, variance]
bn_weights = bn_weights.reshape((4, filters))[[1, 0, 2, 3]]
else:
conv_bias = np.fromfile(fp, dtype=np.float32, count=filters)
# darknet shape (out_dim, in_dim, height, width)
conv_shape = (filters, in_dim, k_size, k_size)
conv_weights = np.fromfile(
fp, dtype=np.float32, count=np.product(conv_shape))
# tf shape (height, width, in_dim, out_dim)
conv_weights = conv_weights.reshape(
conv_shape).transpose([2, 3, 1, 0])
if "batch_normalize" in block:
norm_layer.set_weights(bn_weights)
conv_layer.set_weights([conv_weights])
else:
conv_layer.set_weights([conv_weights, conv_bias])
assert len(fp.read()) == 0, 'failed to read all data'
fp.close()
def main():
weightfile = "yolov3.weights"
cfgfile = "yolov3.cfg"
model_size = (416, 416, 3)
num_classes = 80
model = YOLOv3Net(cfgfile, model_size, num_classes)
load_weights(model, cfgfile, weightfile)
try:
model.save_weights('weights/yolov3_weights.tf')
print('\nThe file \'yolov3_weights.tf\' has been saved successfully.')
except IOError:
print("Couldn't write the file \'yolov3_weights.tf\'.")
if __name__ == '__main__':
main()