目录
- 数据获取
- TFrecord文件
-
- 什么是TFrecord文件
- 将数据转换成TFrecord文件
- 读取TFrecord文件
- 数据处理
- 模型构建
- 模型训练
-
- 模型预测
数据获取

labellmage使用方法


TFrecord文件

什么是TFrecord文件


将数据转换成TFrecord文件

from dataset.vocdata_tfrecord import load_labels,write_to_tfrecord
datapath='./VOCdevkit/VOC2007/'
all_xml=load_labels(datapath,'train')
tfrecord_path='./yolov3/dataset/voc_train.tfrecords'
img_path=os.path.join(datapath,'JPEGImages')
write_to_tfrecord(all_xml,tfrecord_path,img_path)
读取TFrecord文件
from dataset.get_tfdata import getdata
dataset=getdata('./dataset/voc_val.tfrecords')
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from utils.config_utils import read_class_names
classes=read_class_names('config/classname')
plt.figure(15,10)
i=0
for image,width,height,boxes,boxes_category in datasets.take(3):
plt.subplot(1,3,i+1)
plt.imshow(image)
ax=plt.gca()
for j in range(boxes.shape[0]):
rect=Rectangle((boxes[j,0],boxes[j,1]),boxes[j,2] -boxes[j,0],boxes[j,3]-boxes[j,1],color='r',fill=False)
ax.add_patch(rect)
label_id=boxes_category[j]
label=classes.get(label_id.numpy())
ax.text(boxes[j,0],boxes[j,1]+8,label,color='w',size=11,backgroundcolor='none')
i+=1
plt.show()

数据处理

from dataset.preprocess import preprocess
plt.figure(15,10)
i=0
for image,width,height,boxes,boxes_category in datasets.take(3):
image,boxes=preprocess(image,boxes)
plt.subplot(1,3,i+1)
plt.imshow(image)
ax=plt.gca()
for j in range(boxes.shape[0]):
rect=Rectangle((boxes[j,0],boxes[j,1]),boxes[j,2] -boxes[j,0],boxes[j,3]-boxes[j,1],color='r',fill=False)
ax.add_patch(rect)
label_id=boxes_category[j]
label=classes.get(label_id.numpy())
ax.text(boxes[j,0],boxes[j,1]+8,label,color='w',size=11,backgroundcolor='none')
i+=1
plt.show()

模型构建

模型训练
from model.yolov3 import YOLOv3
yolov3=YOLOv3((416,416,3),80)
yolov3.summary()
损失函数的计算

from core.loss import Loss
yolov3_loss=Loss((416,416,3),80)
正负样本的设定

from core.bbox_target import bbox_to_target
for image,width,height,boxes,labels in dataset.take[1]:
label1,label2,label3=bbox_to_target(boxes,label,num_classes=20)
import tensorflow as tf
tf.where(tf.equal(label[...,4],1))
label1[12,12,0,0:4]
label1[12,12,0,5:]
模型训练

获取数据集
from dataset.preprocess import dataset
batch_size=1
trainset=dataset('dataset/voc_train.tfrecords',batch_size)
加载模型
from model.yoloV3 import YOLOv3
yolov3=YOLOv3((416,416,3),20)
from core.loss import Loss
yoloV3_loss=Loss((416,416,3),20)
模型训练


optimizer=tf.keras.optimizers.SGD(learning_rate=0.1,momentum=0.9)
for epoch in range(2):
for (batch,inputs) in enumerate(trainset):
images,labels=inputs
with tf.GradientTape() as Tape:
outputs=yoloV3(image)
loss=yoloV3_loss([*outputs,*labels])
grads=Tape.gradient(loss,yolov3.trainable_variables)
optimizer.apply_gradients(zip(grads,yolov3.trainable_variables))
print(loss)
yolov3.save('yolov3.h5')
模型预测

img=cv2.imread('image.jpg')
predicter=Predict(class_num=80,yolov3='weights/yolov3.h5')
boundings=predicter(img)
plt.imshow(img[:,:,::-1])

