这是YOLO V3的代码,只有网络模型的,嘿嘿嘿嘿嘿
1.darknet.py
import tensorflow as tf
from tensorflow.keras import layers, Sequential
from tensorflow.keras.initializers import RandomNormal
from tensorflow.keras.regularizers import l1, l2
def Conv_BN_Leaky(filters, ks, strides=(1,1)):
lay = Sequential([
layers.Conv2D(filters, ks, strides=strides, padding="same",
kernel_initializer=tf.random_normal_initializer(stddev=0.02), kernel_regularizer=l2(5e-4), use_bias=False),
layers.BatchNormalization(),
layers.LeakyReLU(alpha=0.1)
])
return lay
def resblock_body(inp, filters, blocks):
# x = layers.ZeroPadding2D(((1,0), (1,0)))(inp)
x = Conv_BN_Leaky(filters, (3, 3), strides=(2, 2))(inp)
for i in range(blocks):
y = Conv_BN_Leaky(filters//2, (1,1))(x) # 降维
y = Conv_BN_Leaky(filters//2, (3, 3))(y) # 卷积
y = Conv_BN_Leaky(filters, (1,1))(y) # 升维
x = layers.add([x, y]) # 残差相加
return x
def darknet_body(x):
# 1.先进行一次3x3卷积
x = Conv_BN_Leaky(filters=32, ks=(3,3))(x)
# 2.resblock_body x 1次
x = resblock_body(inp=x, filters=64, blocks=1)
# 3.resblock_body x 2次
x = resblock_body(inp=x, filters=128, blocks=2)
# 4.resblock_body x 8次
x = resblock_body(inp=x, filters=256, blocks=8)
feat1 = x
# 5.resblock_body x 8次
x = resblock_body(inp=x, filters=512, blocks=8)
feat2 = x
# 6.resblock_body x 4次
x = resblock_body(inp=x, filters=1024, blocks=4)
feat3 = x
return feat1, feat2, feat3
if __name__ == '__main__':
from tensorflow.keras.layers import Input
inputs = Input(shape=(416, 416, 3))
feat1, feat2, feat3 = darknet_body(inputs)
print(feat3.shape)
2:? ?yolo.py
import tensorflow as tf
from tensorflow.keras import Sequential,layers
from darknet import *
def make_five_conv(x, filters):
x= Conv_BN_Leaky(filters, (1,1))(x)
x= Conv_BN_Leaky(filters*2, (3,3))(x)
x= Conv_BN_Leaky(filters, (1,1))(x)
x= Conv_BN_Leaky(filters*2, (3,3))(x)
x= Conv_BN_Leaky(filters, (1,1))(x)
return x
def last_conv(x, out_filters):
x = Conv_BN_Leaky(out_filters, (3,3))(x)
y = layers.Conv2D(out_filters, (1, 1), padding="same", kernel_initializer=tf.random_normal_initializer(stddev=0.02), kernel_regularizer=l2(5e-4), use_bias=False)(x)
return y
def YOLO_V3(inputs, nc):
feat_big, feat_middle, feat_small = darknet_body(inputs)
# 第一部分:
feat_small = make_five_conv(feat_small, 512)
print("feat small shape:", feat_small)
out_small = last_conv(feat_small, nc*3)
# 第二部分:
feat_small = Conv_BN_Leaky(256, (1,1))(feat_small)
up_middle = layers.UpSampling2D()(feat_small)
middle_cat = layers.Concatenate()([up_middle, feat_middle])
middle_set = make_five_conv(middle_cat, 256)
out_middle = last_conv(middle_set, nc*3)
# 第三部分:
feat_middle = Conv_BN_Leaky(128, (1,1))(middle_set)
up_big = layers.UpSampling2D()(feat_middle)
big_cat = layers.Concatenate()([up_big, feat_big])
big_set = make_five_conv(big_cat, 128)
out_big = last_conv(big_set, nc*3)
return out_small, out_middle, out_big
if __name__ == '__main__':
from tensorflow.keras.layers import Input
inputs = Input(shape=(416, 416, 3))
feat1, feat2, feat3 = YOLO_V3(inputs, nc=20)
print(feat3.shape)
|