睿智的目标检测48——Tensorflow2 搭建自己的Centernet目标检测平台

迈不过友情╰ 2022-10-28 03:41 564阅读 0赞

睿智的目标检测48——Tensorflow2 搭建自己的Centernet目标检测平台

  • 学习前言
  • 什么是Centernet目标检测算法
  • 源码下载
  • Centernet实现思路
    • 一、预测部分
      • 1、主干网络介绍
      • 2、利用初步特征获得高分辨率特征图
      • 3、Center Head从特征获取预测结果
      • 4、预测结果的解码
      • 5、在原图上进行绘制
    • 二、训练部分
      • 1、真实框的处理
      • 2、利用处理完的真实框与对应图片的预测结果计算loss
  • 训练自己的Centernet模型
    • 一、数据集的准备
    • 二、数据集的处理
    • 三、开始网络训练
    • 四、训练结果预测

学习前言

Tensorflow2版本的实现也要做一下。
在这里插入图片描述

什么是Centernet目标检测算法

在这里插入图片描述
如今常见的目标检测算法通常使用先验框的设定,即先在图片上设定大量的先验框,网络的预测结果会对先验框进行调整获得预测框,先验框很大程度上提高了网络的检测能力,但是也会收到物体尺寸的限制。

Centernet采用不同的方法,构建模型时将目标作为一个点——即目标BBox的中心点。

Centernet的检测器采用关键点估计来找到中心点,并回归到其他目标属性。
在这里插入图片描述
论文中提到:模型是端到端可微的,更简单,更快,更精确。Centernet的模型实现了速度和精确的很好权衡。

源码下载

https://github.com/bubbliiiing/centernet-tf2
喜欢的可以点个star噢。

Centernet实现思路

一、预测部分

1、主干网络介绍

Centernet用到的主干特征网络有多种,一般是以Hourglass Network、DLANet或者Resnet为主干特征提取网络,由于centernet所用到的Hourglass Network参数量太大,有19000W参数,DLANet并没有keras资源,本文以Resnet为例子进行解析。

ResNet50有两个基本的块,分别名为Conv Block和Identity Block,其中Conv Block输入和输出的维度是不一样的,所以不能连续串联,它的作用是改变网络的维度;Identity Block输入维度和输出维度相同,可以串联,用于加深网络的。
Conv Block的结构如下:
在这里插入图片描述
Identity Block的结构如下:
在这里插入图片描述
这两个都是残差网络结构。
当我们输入的图片是512x512x3的时候,整体的特征层shape变化为:
在这里插入图片描述
我们取出最终一个block的输出进行下一步的处理。也就是图上的C5,它的shape为16x16x2048。利用主干特征提取网络,我们获取到了一个初步的特征层,其shape为16x16x2048。

  1. #-------------------------------------------------------------#
  2. # ResNet50的网络部分
  3. #-------------------------------------------------------------#
  4. import numpy as np
  5. import tensorflow.keras.backend as K
  6. from tensorflow.keras import layers
  7. from tensorflow.keras.layers import (Activation, AveragePooling2D,
  8. BatchNormalization, Conv2D,
  9. Conv2DTranspose, Dense, Dropout, Flatten,
  10. Input, MaxPooling2D, ZeroPadding2D)
  11. from tensorflow.keras.models import Model
  12. from tensorflow.keras.preprocessing import image
  13. from tensorflow.keras.regularizers import l2
  14. def identity_block(input_tensor, kernel_size, filters, stage, block):
  15. filters1, filters2, filters3 = filters
  16. conv_name_base = 'res' + str(stage) + block + '_branch'
  17. bn_name_base = 'bn' + str(stage) + block + '_branch'
  18. x = Conv2D(filters1, (1, 1), name=conv_name_base + '2a', use_bias=False)(input_tensor)
  19. x = BatchNormalization(name=bn_name_base + '2a')(x)
  20. x = Activation('relu')(x)
  21. x = Conv2D(filters2, kernel_size,padding='same', name=conv_name_base + '2b', use_bias=False)(x)
  22. x = BatchNormalization(name=bn_name_base + '2b')(x)
  23. x = Activation('relu')(x)
  24. x = Conv2D(filters3, (1, 1), name=conv_name_base + '2c', use_bias=False)(x)
  25. x = BatchNormalization(name=bn_name_base + '2c')(x)
  26. x = layers.add([x, input_tensor])
  27. x = Activation('relu')(x)
  28. return x
  29. def conv_block(input_tensor, kernel_size, filters, stage, block, strides=(2, 2)):
  30. filters1, filters2, filters3 = filters
  31. conv_name_base = 'res' + str(stage) + block + '_branch'
  32. bn_name_base = 'bn' + str(stage) + block + '_branch'
  33. x = Conv2D(filters1, (1, 1), strides=strides,
  34. name=conv_name_base + '2a', use_bias=False)(input_tensor)
  35. x = BatchNormalization(name=bn_name_base + '2a')(x)
  36. x = Activation('relu')(x)
  37. x = Conv2D(filters2, kernel_size, padding='same',
  38. name=conv_name_base + '2b', use_bias=False)(x)
  39. x = BatchNormalization(name=bn_name_base + '2b')(x)
  40. x = Activation('relu')(x)
  41. x = Conv2D(filters3, (1, 1), name=conv_name_base + '2c', use_bias=False)(x)
  42. x = BatchNormalization(name=bn_name_base + '2c')(x)
  43. shortcut = Conv2D(filters3, (1, 1), strides=strides,
  44. name=conv_name_base + '1', use_bias=False)(input_tensor)
  45. shortcut = BatchNormalization(name=bn_name_base + '1')(shortcut)
  46. x = layers.add([x, shortcut])
  47. x = Activation('relu')(x)
  48. return x
  49. def ResNet50(inputs):
  50. # 512x512x3
  51. x = ZeroPadding2D((3, 3))(inputs)
  52. # 256,256,64
  53. x = Conv2D(64, (7, 7), strides=(2, 2), name='conv1', use_bias=False)(x)
  54. x = BatchNormalization(name='bn_conv1')(x)
  55. x = Activation('relu')(x)
  56. # 256,256,64 -> 128,128,64
  57. x = MaxPooling2D((3, 3), strides=(2, 2), padding="same")(x)
  58. # 128,128,64 -> 128,128,256
  59. x = conv_block(x, 3, [64, 64, 256], stage=2, block='a', strides=(1, 1))
  60. x = identity_block(x, 3, [64, 64, 256], stage=2, block='b')
  61. x = identity_block(x, 3, [64, 64, 256], stage=2, block='c')
  62. # 128,128,256 -> 64,64,512
  63. x = conv_block(x, 3, [128, 128, 512], stage=3, block='a')
  64. x = identity_block(x, 3, [128, 128, 512], stage=3, block='b')
  65. x = identity_block(x, 3, [128, 128, 512], stage=3, block='c')
  66. x = identity_block(x, 3, [128, 128, 512], stage=3, block='d')
  67. # 64,64,512 -> 32,32,1024
  68. x = conv_block(x, 3, [256, 256, 1024], stage=4, block='a')
  69. x = identity_block(x, 3, [256, 256, 1024], stage=4, block='b')
  70. x = identity_block(x, 3, [256, 256, 1024], stage=4, block='c')
  71. x = identity_block(x, 3, [256, 256, 1024], stage=4, block='d')
  72. x = identity_block(x, 3, [256, 256, 1024], stage=4, block='e')
  73. x = identity_block(x, 3, [256, 256, 1024], stage=4, block='f')
  74. # 32,32,1024 -> 16,16,2048
  75. x = conv_block(x, 3, [512, 512, 2048], stage=5, block='a')
  76. x = identity_block(x, 3, [512, 512, 2048], stage=5, block='b')
  77. x = identity_block(x, 3, [512, 512, 2048], stage=5, block='c')
  78. return x

2、利用初步特征获得高分辨率特征图

在这里插入图片描述
利用上一步获得到的resnet50的最后一个特征层的shape为(16,16,2048)。

对于该特征层,centernet利用三次反卷积进行上采样,从而更高的分辨率输出。为了节省计算量,这3个反卷积的输出通道数分别为256,128,64。

每一次反卷积,特征层的高和宽会变为原来的两倍,因此,在进行三次反卷积上采样后,我们获得的特征层的高和宽变为原来的8倍,此时特征层的高和宽为128x128,通道数为64。

此时我们获得了一个128x128x64的有效特征层(高分辨率特征图),我们会利用该有效特征层获得最终的预测结果。
在这里插入图片描述
实现代码如下:

  1. x = Dropout(rate=0.5)(x)
  2. #-------------------------------#
  3. # 解码器
  4. #-------------------------------#
  5. num_filters = 256
  6. # 16, 16, 2048 -> 32, 32, 256 -> 64, 64, 128 -> 128, 128, 64
  7. for i in range(3):
  8. # 进行上采样
  9. x = Conv2DTranspose(num_filters // pow(2, i), (4, 4), strides=2, use_bias=False, padding='same',
  10. kernel_initializer='he_normal',
  11. kernel_regularizer=l2(5e-4))(x)
  12. x = BatchNormalization()(x)
  13. x = Activation('relu')(x)

3、Center Head从特征获取预测结果

在这里插入图片描述
通过上一步我们可以获得一个128x128x64的高分辨率特征图。

这个特征层相当于将整个图片划分成128x128个区域,每个区域存在一个特征点,如果某个物体的中心落在这个区域,那么就由这个特征点来确定。
某个物体的中心落在这个区域,则由这个区域左上角的特征点来约定

我们可以利用这个特征层进行三个卷积,分别是:
1、热力图预测,此时卷积的通道数为num_classes,最终结果为(128,128,num_classes),代表每一个热力点是否有物体存在,以及物体的种类;
2、中心点预测,此时卷积的通道数为2,最终结果为(128,128,2),代表每一个物体中心距离热力点偏移的情况;
3、宽高预测,此时卷积的通道数为2,最终结果为(128,128,2),代表每一个物体宽高的预测情况;

实现代码为:

  1. def centernet_head(x,num_classes):
  2. x = Dropout(rate=0.5)(x)
  3. #-------------------------------#
  4. # 解码器
  5. #-------------------------------#
  6. num_filters = 256
  7. # 16, 16, 2048 -> 32, 32, 256 -> 64, 64, 128 -> 128, 128, 64
  8. for i in range(3):
  9. # 进行上采样
  10. x = Conv2DTranspose(num_filters // pow(2, i), (4, 4), strides=2, use_bias=False, padding='same',
  11. kernel_initializer='he_normal',
  12. kernel_regularizer=l2(5e-4))(x)
  13. x = BatchNormalization()(x)
  14. x = Activation('relu')(x)
  15. # 最终获得128,128,64的特征层
  16. # hm header
  17. y1 = Conv2D(64, 3, padding='same', use_bias=False, kernel_initializer='he_normal', kernel_regularizer=l2(5e-4))(x)
  18. y1 = BatchNormalization()(y1)
  19. y1 = Activation('relu')(y1)
  20. y1 = Conv2D(num_classes, 1, kernel_initializer='he_normal', kernel_regularizer=l2(5e-4), activation='sigmoid')(y1)
  21. # wh header
  22. y2 = Conv2D(64, 3, padding='same', use_bias=False, kernel_initializer='he_normal', kernel_regularizer=l2(5e-4))(x)
  23. y2 = BatchNormalization()(y2)
  24. y2 = Activation('relu')(y2)
  25. y2 = Conv2D(2, 1, kernel_initializer='he_normal', kernel_regularizer=l2(5e-4))(y2)
  26. # reg header
  27. y3 = Conv2D(64, 3, padding='same', use_bias=False, kernel_initializer='he_normal', kernel_regularizer=l2(5e-4))(x)
  28. y3 = BatchNormalization()(y3)
  29. y3 = Activation('relu')(y3)
  30. y3 = Conv2D(2, 1, kernel_initializer='he_normal', kernel_regularizer=l2(5e-4))(y3)
  31. return y1, y2, y3

4、预测结果的解码

在对预测结果进行解码之前,我们再来看看预测结果代表了什么,预测结果可以分为3个部分:

1、heatmap热力图预测,此时卷积的通道数为num_classes,最终结果为(128,128,num_classes),代表每一个热力点是否有物体存在,以及物体的种类,最后一维度num_classes中的预测值代表属于每一个类的概率;
2、reg中心点预测,此时卷积的通道数为2,最终结果为(128,128,2),代表每一个物体中心距离热力点偏移的情况,最后一维度2中的预测值代表当前这个特征点向右下角偏移的情况;
3、wh宽高预测,此时卷积的通道数为2,最终结果为(128,128,2),代表每一个物体宽高的预测情况,最后一维度2中的预测值代表当前这个特征点对应的预测框的宽高;

特征层相当于将图像划分成128x128个特征点每个特征点负责预测中心落在其右下角一片区域的物体。在这里插入图片描述

如图所示,蓝色的点为128x128的特征点,此时我们对左图红色的三个点进行解码操作演示:
1、进行中心点偏移,利用reg中心点预测对特征点坐标进行偏移,左图红色的三个特征点偏移后是右图橙色的三个点;
2、利用中心点加上和减去 wh宽高预测结果除以2,获得预测框的左上角和右下角。
3、此时获得的预测框就可以绘制在图片上了。
在这里插入图片描述
除去这样的解码操作,还有非极大抑制的操作需要进行,防止同一种类的框的堆积。

在论文中所说,centernet不像其它目标检测算法,在解码之后需要进行非极大抑制,centernet的非极大抑制在解码之前进行。采用的方法是最大池化利用3x3的池化核在热力图上搜索,然后只保留一定区域内得分最大的框。

在实际使用时发现,当目标为小目标时,确实可以不在解码之后进行非极大抑制的后处理,如果目标为大目标,网络无法正确判断目标的中心时,还是需要进行非击大抑制的后处理的。

  1. def nms(heat, kernel=3):
  2. hmax = MaxPooling2D((kernel, kernel), strides=1, padding='SAME')(heat)
  3. heat = tf.where(tf.equal(hmax, heat), heat, tf.zeros_like(heat))
  4. return heat
  5. def topk(hm, max_objects=100):
  6. # hm -> Hot map热力图
  7. # 进行热力图的非极大抑制,利用3x3的卷积对热力图进行Max筛选,找出值最大的
  8. hm = nms(hm)
  9. # (b, h * w * c)
  10. b, h, w, c = tf.shape(hm)[0], tf.shape(hm)[1], tf.shape(hm)[2], tf.shape(hm)[3]
  11. # 将所有结果平铺,获得(b, h * w * c)
  12. hm = tf.reshape(hm, (b, -1))
  13. # (b, k), (b, k)
  14. scores, indices = tf.math.top_k(hm, k=max_objects, sorted=True)
  15. # 计算求出网格点,类别
  16. class_ids = indices % c
  17. xs = indices // c % w
  18. ys = indices // c // w
  19. indices = ys * w + xs
  20. return scores, indices, class_ids, xs, ys
  21. def decode(hm, wh, reg, max_objects=100,num_classes=20):
  22. scores, indices, class_ids, xs, ys = topk(hm, max_objects=max_objects)
  23. # 获得batch_size
  24. b = tf.shape(hm)[0]
  25. # (b, h * w, 2)
  26. reg = tf.reshape(reg, [b, -1, 2])
  27. # (b, h * w, 2)
  28. wh = tf.reshape(wh, [b, -1, 2])
  29. length = tf.shape(wh)[1]
  30. # 找到其在1维上的索引
  31. batch_idx = tf.expand_dims(tf.range(0, b), 1)
  32. batch_idx = tf.tile(batch_idx, (1, max_objects))
  33. full_indices = tf.reshape(batch_idx, [-1]) * tf.to_int32(length) + tf.reshape(indices, [-1])
  34. # 取出top_k个框对应的参数
  35. topk_reg = tf.gather(tf.reshape(reg, [-1,2]), full_indices)
  36. topk_reg = tf.reshape(topk_reg, [b, -1, 2])
  37. topk_wh = tf.gather(tf.reshape(wh, [-1,2]), full_indices)
  38. topk_wh = tf.reshape(topk_wh, [b, -1, 2])
  39. # 计算调整后的中心
  40. topk_cx = tf.cast(tf.expand_dims(xs, axis=-1), tf.float32) + topk_reg[..., 0:1]
  41. topk_cy = tf.cast(tf.expand_dims(ys, axis=-1), tf.float32) + topk_reg[..., 1:2]
  42. # (b,k,1) (b,k,1)
  43. topk_x1, topk_y1 = topk_cx - topk_wh[..., 0:1] / 2, topk_cy - topk_wh[..., 1:2] / 2
  44. # (b,k,1) (b,k,1)
  45. topk_x2, topk_y2 = topk_cx + topk_wh[..., 0:1] / 2, topk_cy + topk_wh[..., 1:2] / 2
  46. # (b,k,1)
  47. scores = tf.expand_dims(scores, axis=-1)
  48. # (b,k,1)
  49. class_ids = tf.cast(tf.expand_dims(class_ids, axis=-1), tf.float32)
  50. # (b,k,6)
  51. detections = tf.concat([topk_x1, topk_y1, topk_x2, topk_y2, scores, class_ids], axis=-1)
  52. return detections

5、在原图上进行绘制

通过第三步,我们可以获得预测框在原图上的位置,而且这些预测框都是经过筛选的。这些筛选后的框可以直接绘制在图片上,就可以获得结果了。

二、训练部分

1、真实框的处理

既然在centernet中,物体的中心落在哪个特征点的右下角就由哪个特征点来负责预测,那么在训练的时候我们就需要找到真实框和特征点之间的关系。

真实框和特征点之间的关系,对应方式如下:
1、找到真实框的中心,通过真实框的中心找到其对应的特征点。
2、根据该真实框的种类,对网络应该有的热力图进行设置,即heatmap热力图。其实就是将对应的特征点里面的对应的种类,它的中心值设置为1,然后这个特征点附近的其它特征点中该种类对应的值按照高斯分布不断下降
在这里插入图片描述
3、除去heatmap热力图外,还需要设置特征点对应的reg中心点和wh宽高,在找到真实框对应的特征点后,还需要设置该特征点对应的reg中心和wh宽高。这里的reg中心和wh宽高都是对于128x128的特征层的。
4、在获得网络应该有的预测结果后,就可以将预测结果和应该有的预测结果进行对比,对网络进行反向梯度调整了。

实现代码如下:

  1. import math
  2. from random import shuffle
  3. import cv2
  4. import numpy as np
  5. from PIL import Image
  6. from tensorflow import keras
  7. from utils.utils import cvtColor, preprocess_input
  8. def draw_gaussian(heatmap, center, radius, k=1):
  9. diameter = 2 * radius + 1
  10. gaussian = gaussian2D((diameter, diameter), sigma=diameter / 6)
  11. x, y = int(center[0]), int(center[1])
  12. height, width = heatmap.shape[0:2]
  13. left, right = min(x, radius), min(width - x, radius + 1)
  14. top, bottom = min(y, radius), min(height - y, radius + 1)
  15. masked_heatmap = heatmap[y - top:y + bottom, x - left:x + right]
  16. masked_gaussian = gaussian[radius - top:radius + bottom, radius - left:radius + right]
  17. if min(masked_gaussian.shape) > 0 and min(masked_heatmap.shape) > 0: # TODO debug
  18. np.maximum(masked_heatmap, masked_gaussian * k, out=masked_heatmap)
  19. return heatmap
  20. def gaussian2D(shape, sigma=1):
  21. m, n = [(ss - 1.) / 2. for ss in shape]
  22. y, x = np.ogrid[-m:m + 1, -n:n + 1]
  23. h = np.exp(-(x * x + y * y) / (2 * sigma * sigma))
  24. h[h < np.finfo(h.dtype).eps * h.max()] = 0
  25. return h
  26. def gaussian_radius(det_size, min_overlap=0.7):
  27. height, width = det_size
  28. a1 = 1
  29. b1 = (height + width)
  30. c1 = width * height * (1 - min_overlap) / (1 + min_overlap)
  31. sq1 = np.sqrt(b1 ** 2 - 4 * a1 * c1)
  32. r1 = (b1 + sq1) / 2
  33. a2 = 4
  34. b2 = 2 * (height + width)
  35. c2 = (1 - min_overlap) * width * height
  36. sq2 = np.sqrt(b2 ** 2 - 4 * a2 * c2)
  37. r2 = (b2 + sq2) / 2
  38. a3 = 4 * min_overlap
  39. b3 = -2 * min_overlap * (height + width)
  40. c3 = (min_overlap - 1) * width * height
  41. sq3 = np.sqrt(b3 ** 2 - 4 * a3 * c3)
  42. r3 = (b3 + sq3) / 2
  43. return min(r1, r2, r3)
  44. class CenternetDatasets(keras.utils.Sequence):
  45. def __init__(self, annotation_lines, input_shape, batch_size, num_classes, train, max_objects = 100):
  46. self.annotation_lines = annotation_lines
  47. self.length = len(self.annotation_lines)
  48. self.input_shape = input_shape
  49. self.output_shape = (int(input_shape[0]/4), int(input_shape[1]/4))
  50. self.batch_size = batch_size
  51. self.num_classes = num_classes
  52. self.train = train
  53. self.max_objects = max_objects
  54. def __len__(self):
  55. return math.ceil(len(self.annotation_lines) / float(self.batch_size))
  56. def __getitem__(self, index):
  57. batch_images = np.zeros((self.batch_size, self.input_shape[0], self.input_shape[1], 3), dtype=np.float32)
  58. batch_hms = np.zeros((self.batch_size, self.output_shape[0], self.output_shape[1], self.num_classes), dtype=np.float32)
  59. batch_whs = np.zeros((self.batch_size, self.max_objects, 2), dtype=np.float32)
  60. batch_regs = np.zeros((self.batch_size, self.max_objects, 2), dtype=np.float32)
  61. batch_reg_masks = np.zeros((self.batch_size, self.max_objects), dtype=np.float32)
  62. batch_indices = np.zeros((self.batch_size, self.max_objects), dtype=np.float32)
  63. for b, i in enumerate(range(index * self.batch_size, (index + 1) * self.batch_size)):
  64. i = i % self.length
  65. #---------------------------------------------------#
  66. # 训练时进行数据的随机增强
  67. # 验证时不进行数据的随机增强
  68. #---------------------------------------------------#
  69. image, box = self.get_random_data(self.annotation_lines[i], self.input_shape, random = self.train)
  70. if len(box) != 0:
  71. boxes = np.array(box[:, :4],dtype=np.float32)
  72. boxes[:, [0, 2]] = np.clip(boxes[:, [0, 2]] / self.input_shape[1] * self.output_shape[1], 0, self.output_shape[1] - 1)
  73. boxes[:, [1, 3]] = np.clip(boxes[:, [1, 3]] / self.input_shape[0] * self.output_shape[0], 0, self.output_shape[0] - 1)
  74. for i in range(len(box)):
  75. bbox = boxes[i].copy()
  76. cls_id = int(box[i, -1])
  77. h, w = bbox[3] - bbox[1], bbox[2] - bbox[0]
  78. if h > 0 and w > 0:
  79. radius = gaussian_radius((math.ceil(h), math.ceil(w)))
  80. radius = max(0, int(radius))
  81. #-------------------------------------------------#
  82. # 计算真实框所属的特征点
  83. #-------------------------------------------------#
  84. ct = np.array([(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2], dtype=np.float32)
  85. ct_int = ct.astype(np.int32)
  86. #----------------------------#
  87. # 绘制高斯热力图
  88. #----------------------------#
  89. batch_hms[b, :, :, cls_id] = draw_gaussian(batch_hms[b, :, :, cls_id], ct_int, radius)
  90. #---------------------------------------------------#
  91. # 计算宽高真实值
  92. #---------------------------------------------------#
  93. batch_whs[b, i] = 1. * w, 1. * h
  94. #---------------------------------------------------#
  95. # 计算中心偏移量
  96. #---------------------------------------------------#
  97. batch_regs[b, i] = ct - ct_int
  98. #---------------------------------------------------#
  99. # 将对应的mask设置为1,用于排除多余的0
  100. #---------------------------------------------------#
  101. batch_reg_masks[b, i] = 1
  102. #---------------------------------------------------#
  103. # 表示第ct_int[1]行的第ct_int[0]个。
  104. #---------------------------------------------------#
  105. batch_indices[b, i] = ct_int[1] * self.output_shape[0] + ct_int[0]
  106. batch_images[b] = preprocess_input(image)
  107. return [batch_images, batch_hms, batch_whs, batch_regs, batch_reg_masks, batch_indices], np.zeros((self.batch_size,))
  108. def generate(self):
  109. i = 0
  110. while True:
  111. batch_images = np.zeros((self.batch_size, self.input_shape[0], self.input_shape[1], 3), dtype=np.float32)
  112. batch_hms = np.zeros((self.batch_size, self.output_shape[0], self.output_shape[1], self.num_classes), dtype=np.float32)
  113. batch_whs = np.zeros((self.batch_size, self.max_objects, 2), dtype=np.float32)
  114. batch_regs = np.zeros((self.batch_size, self.max_objects, 2), dtype=np.float32)
  115. batch_reg_masks = np.zeros((self.batch_size, self.max_objects), dtype=np.float32)
  116. batch_indices = np.zeros((self.batch_size, self.max_objects), dtype=np.float32)
  117. for b in range(self.batch_size):
  118. #---------------------------------------------------#
  119. # 训练时进行数据的随机增强
  120. # 验证时不进行数据的随机增强
  121. #---------------------------------------------------#
  122. image, box = self.get_random_data(self.annotation_lines[i], self.input_shape, random = self.train)
  123. if len(box) != 0:
  124. boxes = np.array(box[:, :4],dtype=np.float32)
  125. boxes[:, [0, 2]] = np.clip(boxes[:, [0, 2]] / self.input_shape[1] * self.output_shape[1], 0, self.output_shape[1] - 1)
  126. boxes[:, [1, 3]] = np.clip(boxes[:, [1, 3]] / self.input_shape[0] * self.output_shape[0], 0, self.output_shape[0] - 1)
  127. for i in range(len(box)):
  128. bbox = boxes[i].copy()
  129. cls_id = int(box[i, -1])
  130. h, w = bbox[3] - bbox[1], bbox[2] - bbox[0]
  131. if h > 0 and w > 0:
  132. radius = gaussian_radius((math.ceil(h), math.ceil(w)))
  133. radius = max(0, int(radius))
  134. #-------------------------------------------------#
  135. # 计算真实框所属的特征点
  136. #-------------------------------------------------#
  137. ct = np.array([(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2], dtype=np.float32)
  138. ct_int = ct.astype(np.int32)
  139. #----------------------------#
  140. # 绘制高斯热力图
  141. #----------------------------#
  142. batch_hms[b, :, :, cls_id] = draw_gaussian(batch_hms[b, :, :, cls_id], ct_int, radius)
  143. #---------------------------------------------------#
  144. # 计算宽高真实值
  145. #---------------------------------------------------#
  146. batch_whs[b, i] = 1. * w, 1. * h
  147. #---------------------------------------------------#
  148. # 计算中心偏移量
  149. #---------------------------------------------------#
  150. batch_regs[b, i] = ct - ct_int
  151. #---------------------------------------------------#
  152. # 将对应的mask设置为1,用于排除多余的0
  153. #---------------------------------------------------#
  154. batch_reg_masks[b, i] = 1
  155. #---------------------------------------------------#
  156. # 表示第ct_int[1]行的第ct_int[0]个。
  157. #---------------------------------------------------#
  158. batch_indices[b, i] = ct_int[1] * self.output_shape[0] + ct_int[0]
  159. batch_images[b] = preprocess_input(image)
  160. yield batch_images, batch_hms, batch_whs, batch_regs, batch_reg_masks, batch_indices
  161. def rand(self, a=0, b=1):
  162. return np.random.rand()*(b-a) + a
  163. def get_random_data(self, annotation_line, input_shape, jitter=.3, hue=.1, sat=1.5, val=1.5, random=True):
  164. line = annotation_line.split()
  165. #------------------------------#
  166. # 读取图像并转换成RGB图像
  167. #------------------------------#
  168. image = Image.open(line[0])
  169. image = cvtColor(image)
  170. #------------------------------#
  171. # 获得图像的高宽与目标高宽
  172. #------------------------------#
  173. iw, ih = image.size
  174. h, w = input_shape
  175. #------------------------------#
  176. # 获得预测框
  177. #------------------------------#
  178. box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]])
  179. if not random:
  180. scale = min(w/iw, h/ih)
  181. nw = int(iw*scale)
  182. nh = int(ih*scale)
  183. dx = (w-nw)//2
  184. dy = (h-nh)//2
  185. #---------------------------------#
  186. # 将图像多余的部分加上灰条
  187. #---------------------------------#
  188. image = image.resize((nw,nh), Image.BICUBIC)
  189. new_image = Image.new('RGB', (w,h), (128,128,128))
  190. new_image.paste(image, (dx, dy))
  191. image_data = np.array(new_image, np.float32)
  192. #---------------------------------#
  193. # 对真实框进行调整
  194. #---------------------------------#
  195. if len(box)>0:
  196. np.random.shuffle(box)
  197. box[:, [0,2]] = box[:, [0,2]]*nw/iw + dx
  198. box[:, [1,3]] = box[:, [1,3]]*nh/ih + dy
  199. box[:, 0:2][box[:, 0:2]<0] = 0
  200. box[:, 2][box[:, 2]>w] = w
  201. box[:, 3][box[:, 3]>h] = h
  202. box_w = box[:, 2] - box[:, 0]
  203. box_h = box[:, 3] - box[:, 1]
  204. box = box[np.logical_and(box_w>1, box_h>1)] # discard invalid box
  205. return image_data, box
  206. #------------------------------------------#
  207. # 对图像进行缩放并且进行长和宽的扭曲
  208. #------------------------------------------#
  209. new_ar = w/h * self.rand(1-jitter,1+jitter) / self.rand(1-jitter,1+jitter)
  210. scale = self.rand(.25, 2)
  211. if new_ar < 1:
  212. nh = int(scale*h)
  213. nw = int(nh*new_ar)
  214. else:
  215. nw = int(scale*w)
  216. nh = int(nw/new_ar)
  217. image = image.resize((nw,nh), Image.BICUBIC)
  218. #------------------------------------------#
  219. # 将图像多余的部分加上灰条
  220. #------------------------------------------#
  221. dx = int(self.rand(0, w-nw))
  222. dy = int(self.rand(0, h-nh))
  223. new_image = Image.new('RGB', (w,h), (128,128,128))
  224. new_image.paste(image, (dx, dy))
  225. image = new_image
  226. #------------------------------------------#
  227. # 翻转图像
  228. #------------------------------------------#
  229. flip = self.rand()<.5
  230. if flip: image = image.transpose(Image.FLIP_LEFT_RIGHT)
  231. #------------------------------------------#
  232. # 色域扭曲
  233. #------------------------------------------#
  234. hue = self.rand(-hue, hue)
  235. sat = self.rand(1, sat) if self.rand()<.5 else 1/self.rand(1, sat)
  236. val = self.rand(1, val) if self.rand()<.5 else 1/self.rand(1, val)
  237. x = cv2.cvtColor(np.array(image,np.float32)/255, cv2.COLOR_RGB2HSV)
  238. x[..., 0] += hue*360
  239. x[..., 0][x[..., 0]>1] -= 1
  240. x[..., 0][x[..., 0]<0] += 1
  241. x[..., 1] *= sat
  242. x[..., 2] *= val
  243. x[x[:,:, 0]>360, 0] = 360
  244. x[:, :, 1:][x[:, :, 1:]>1] = 1
  245. x[x<0] = 0
  246. image_data = cv2.cvtColor(x, cv2.COLOR_HSV2RGB)*255 # numpy array, 0 to 1
  247. #---------------------------------#
  248. # 对真实框进行调整
  249. #---------------------------------#
  250. if len(box)>0:
  251. np.random.shuffle(box)
  252. box[:, [0,2]] = box[:, [0,2]]*nw/iw + dx
  253. box[:, [1,3]] = box[:, [1,3]]*nh/ih + dy
  254. if flip: box[:, [0,2]] = w - box[:, [2,0]]
  255. box[:, 0:2][box[:, 0:2]<0] = 0
  256. box[:, 2][box[:, 2]>w] = w
  257. box[:, 3][box[:, 3]>h] = h
  258. box_w = box[:, 2] - box[:, 0]
  259. box_h = box[:, 3] - box[:, 1]
  260. box = box[np.logical_and(box_w>1, box_h>1)]
  261. return image_data, box
  262. def on_epoch_begin(self):
  263. shuffle(self.annotation_lines)

2、利用处理完的真实框与对应图片的预测结果计算loss

loss计算分为三个部分,分别是:
1、热力图的loss
2、reg中心点的loss
3、wh宽高的loss

具体情况如下:
1、热力图的loss采用focal loss的思想进行运算,其中 α 和 β 是Focal Loss的超参数,而其中的N是正样本的数量,用于进行标准化。 α 和 β在这篇论文中和分别是2和4。
整体思想和Focal Loss类似,对于容易分类的样本,适当减少其训练比重也就是loss值。
在公式中,带帽子的Y是预测值,不戴帽子的Y是真实值。
在这里插入图片描述
2、reg中心点的loss和wh宽高的loss使用的是普通L1损失函数

在这里插入图片描述

reg中心点预测和wh宽高预测都直接采用了特征层坐标的尺寸,也就是在0到128之内。
由于wh宽高预测的loss会比较大,其loss乘上了一个系数,论文是0.1。
reg中心点预测的系数则为1。

总的loss就变成了:
在这里插入图片描述
实现代码如下:

  1. def focal_loss(hm_pred, hm_true):
  2. # 找到正样本和负样本
  3. pos_mask = tf.cast(tf.equal(hm_true, 1), tf.float32)
  4. # 小于1的都是负样本
  5. neg_mask = tf.cast(tf.less(hm_true, 1), tf.float32)
  6. neg_weights = tf.pow(1 - hm_true, 4)
  7. pos_loss = -tf.log(tf.clip_by_value(hm_pred, 1e-7, 1.)) * tf.pow(1 - hm_pred, 2) * pos_mask
  8. neg_loss = -tf.log(tf.clip_by_value(1 - hm_pred, 1e-7, 1.)) * tf.pow(hm_pred, 2) * neg_weights * neg_mask
  9. num_pos = tf.reduce_sum(pos_mask)
  10. pos_loss = tf.reduce_sum(pos_loss)
  11. neg_loss = tf.reduce_sum(neg_loss)
  12. cls_loss = tf.cond(tf.greater(num_pos, 0), lambda: (pos_loss + neg_loss) / num_pos, lambda: neg_loss)
  13. return cls_loss
  14. def reg_l1_loss(y_pred, y_true, indices, mask):
  15. b, c = tf.shape(y_pred)[0], tf.shape(y_pred)[-1]
  16. k = tf.shape(indices)[1]
  17. y_pred = tf.reshape(y_pred, (b, -1, c))
  18. length = tf.shape(y_pred)[1]
  19. indices = tf.cast(indices, tf.int32)
  20. # 找到其在1维上的索引
  21. batch_idx = tf.expand_dims(tf.range(0, b), 1)
  22. batch_idx = tf.tile(batch_idx, (1, k))
  23. full_indices = (tf.reshape(batch_idx, [-1]) * tf.to_int32(length) +
  24. tf.reshape(indices, [-1]))
  25. # 取出对应的预测值
  26. y_pred = tf.gather(tf.reshape(y_pred, [-1,c]),full_indices)
  27. y_pred = tf.reshape(y_pred, [b, -1, c])
  28. mask = tf.tile(tf.expand_dims(mask, axis=-1), (1, 1, 2))
  29. # 求取l1损失值
  30. total_loss = tf.reduce_sum(tf.abs(y_true * mask - y_pred * mask))
  31. reg_loss = total_loss / (tf.reduce_sum(mask) + 1e-4)
  32. return reg_loss
  33. def loss(args):
  34. #-----------------------------------------------------------------------------------------------------------------#
  35. # hm_pred:热力图的预测值 (self.batch_size, self.output_size[0], self.output_size[1], self.num_classes)
  36. # wh_pred:宽高的预测值 (self.batch_size, self.output_size[0], self.output_size[1], 2)
  37. # reg_pred:中心坐标偏移预测值 (self.batch_size, self.output_size[0], self.output_size[1], 2)
  38. # hm_true:热力图的真实值 (self.batch_size, self.output_size[0], self.output_size[1], self.num_classes)
  39. # wh_true:宽高的真实值 (self.batch_size, self.max_objects, 2)
  40. # reg_true:中心坐标偏移真实值 (self.batch_size, self.max_objects, 2)
  41. # reg_mask:真实值的mask (self.batch_size, self.max_objects)
  42. # indices:真实值对应的坐标 (self.batch_size, self.max_objects)
  43. #-----------------------------------------------------------------------------------------------------------------#
  44. hm_pred, wh_pred, reg_pred, hm_true, wh_true, reg_true, reg_mask, indices = args
  45. hm_loss = focal_loss(hm_pred, hm_true)
  46. wh_loss = 0.1 * reg_l1_loss(wh_pred, wh_true, indices, reg_mask)
  47. reg_loss = reg_l1_loss(reg_pred, reg_true, indices, reg_mask)
  48. total_loss = hm_loss + wh_loss + reg_loss
  49. # total_loss = tf.Print(total_loss,[hm_loss,wh_loss,reg_loss])
  50. return total_loss

训练自己的Centernet模型

首先前往Github下载对应的仓库,下载完后利用解压软件解压,之后用编程软件打开文件夹。
注意打开的根目录必须正确,否则相对目录不正确的情况下,代码将无法运行。

一定要注意打开后的根目录是文件存放的目录。
在这里插入图片描述

一、数据集的准备

本文使用VOC格式进行训练,训练前需要自己制作好数据集,如果没有自己的数据集,可以通过Github连接下载VOC12+07的数据集尝试下。
训练前将标签文件放在VOCdevkit文件夹下的VOC2007文件夹下的Annotation中。
在这里插入图片描述
训练前将图片文件放在VOCdevkit文件夹下的VOC2007文件夹下的JPEGImages中。
在这里插入图片描述
此时数据集的摆放已经结束。

二、数据集的处理

在完成数据集的摆放之后,我们需要对数据集进行下一步的处理,目的是获得训练用的2007_train.txt以及2007_val.txt,需要用到根目录下的voc_annotation.py。

voc_annotation.py里面有一些参数需要设置。
分别是annotation_mode、classes_path、trainval_percent、train_percent、VOCdevkit_path,第一次训练可以仅修改classes_path

  1. '''
  2. annotation_mode用于指定该文件运行时计算的内容
  3. annotation_mode为0代表整个标签处理过程,包括获得VOCdevkit/VOC2007/ImageSets里面的txt以及训练用的2007_train.txt、2007_val.txt
  4. annotation_mode为1代表获得VOCdevkit/VOC2007/ImageSets里面的txt
  5. annotation_mode为2代表获得训练用的2007_train.txt、2007_val.txt
  6. '''
  7. annotation_mode = 0
  8. '''
  9. 必须要修改,用于生成2007_train.txt、2007_val.txt的目标信息
  10. 与训练和预测所用的classes_path一致即可
  11. 如果生成的2007_train.txt里面没有目标信息
  12. 那么就是因为classes没有设定正确
  13. 仅在annotation_mode为0和2的时候有效
  14. '''
  15. classes_path = 'model_data/voc_classes.txt'
  16. '''
  17. trainval_percent用于指定(训练集+验证集)与测试集的比例,默认情况下 (训练集+验证集):测试集 = 9:1
  18. train_percent用于指定(训练集+验证集)中训练集与验证集的比例,默认情况下 训练集:验证集 = 9:1
  19. 仅在annotation_mode为0和1的时候有效
  20. '''
  21. trainval_percent = 0.9
  22. train_percent = 0.9
  23. '''
  24. 指向VOC数据集所在的文件夹
  25. 默认指向根目录下的VOC数据集
  26. '''
  27. VOCdevkit_path = 'VOCdevkit'

classes_path用于指向检测类别所对应的txt,以voc数据集为例,我们用的txt为:
在这里插入图片描述
训练自己的数据集时,可以自己建立一个cls_classes.txt,里面写自己所需要区分的类别。

三、开始网络训练

通过voc_annotation.py我们已经生成了2007_train.txt以及2007_val.txt,此时我们可以开始训练了。
训练的参数较多,大家可以在下载库后仔细看注释,其中最重要的部分依然是train.py里的classes_path。

classes_path用于指向检测类别所对应的txt,这个txt和voc_annotation.py里面的txt一样!训练自己的数据集必须要修改!
在这里插入图片描述

修改完classes_path后就可以运行train.py开始训练了,在训练多个epoch后,权值会生成在logs文件夹中。
其它参数的作用如下:

  1. #----------------------------------------------------#
  2. # 是否使用eager模式训练
  3. #----------------------------------------------------#
  4. eager = False
  5. #--------------------------------------------------------#
  6. # 训练前一定要修改classes_path,使其对应自己的数据集
  7. #--------------------------------------------------------#
  8. classes_path = 'model_data/voc_classes.txt'
  9. #----------------------------------------------------------------------------------------------------------------------------#
  10. # 权值文件请看README,百度网盘下载。数据的预训练权重对不同数据集是通用的,因为特征是通用的。
  11. # 预训练权重对于99%的情况都必须要用,不用的话权值太过随机,特征提取效果不明显,网络训练的结果也不会好。
  12. # 训练自己的数据集时提示维度不匹配正常,预测的东西都不一样了自然维度不匹配
  13. #
  14. # 如果想要断点续练就将model_path设置成logs文件夹下已经训练的权值文件。
  15. # 当model_path = ''的时候不加载整个模型的权值。
  16. #
  17. # 此处使用的是整个模型的权重,因此是在train.py进行加载的。
  18. # 如果想要让模型从主干的预训练权值开始训练,则设置model_path为主干网络的权值,此时仅加载主干。
  19. # 如果想要让模型从0开始训练,则设置model_path = '',Freeze_Train = Fasle,此时从0开始训练,且没有冻结主干的过程。
  20. # 一般来讲,从0开始训练效果会很差,因为权值太过随机,特征提取效果不明显。
  21. #----------------------------------------------------------------------------------------------------------------------------#
  22. model_path = 'model_data/centernet_resnet50_voc.h5'
  23. #------------------------------------------------------#
  24. # 输入的shape大小,32的倍数
  25. #------------------------------------------------------#
  26. input_shape = [512, 512]
  27. #-------------------------------------------#
  28. # 主干特征提取网络的选择
  29. # resnet50和hourglass
  30. #-------------------------------------------#
  31. backbone = "resnet50"
  32. #----------------------------------------------------#
  33. # 训练分为两个阶段,分别是冻结阶段和解冻阶段。
  34. # 显存不足与数据集大小无关,提示显存不足请调小batch_size。
  35. # 受到BatchNorm层影响,batch_size最小为2,不能为1。
  36. #----------------------------------------------------#
  37. #----------------------------------------------------#
  38. # 冻结阶段训练参数
  39. # 此时模型的主干被冻结了,特征提取网络不发生改变
  40. # 占用的显存较小,仅对网络进行微调
  41. #----------------------------------------------------#
  42. Init_Epoch = 0
  43. Freeze_Epoch = 50
  44. Freeze_batch_size = 16
  45. Freeze_lr = 1e-3
  46. #----------------------------------------------------#
  47. # 解冻阶段训练参数
  48. # 此时模型的主干不被冻结了,特征提取网络会发生改变
  49. # 占用的显存较大,网络所有的参数都会发生改变
  50. #----------------------------------------------------#
  51. UnFreeze_Epoch = 100
  52. Unfreeze_batch_size = 8
  53. Unfreeze_lr = 1e-4
  54. #------------------------------------------------------#
  55. # 是否进行冻结训练,默认先冻结主干训练后解冻训练。
  56. #------------------------------------------------------#
  57. Freeze_Train = True
  58. #------------------------------------------------------#
  59. # 用于设置是否使用多线程读取数据,0代表关闭多线程
  60. # 开启后会加快数据读取速度,但是会占用更多内存
  61. # keras里开启多线程有些时候速度反而慢了许多
  62. # 在IO为瓶颈的时候再开启多线程,即GPU运算速度远大于读取图片的速度。
  63. #------------------------------------------------------#
  64. num_workers = 0
  65. #----------------------------------------------------#
  66. # 获得图片路径和标签
  67. #----------------------------------------------------#
  68. train_annotation_path = '2007_train.txt'
  69. val_annotation_path = '2007_val.txt'

四、训练结果预测

训练结果预测需要用到两个文件,分别是yolo.py和predict.py。
我们首先需要去yolo.py里面修改model_path以及classes_path,这两个参数必须要修改。

model_path指向训练好的权值文件,在logs文件夹里。
classes_path指向检测类别所对应的txt。

在这里插入图片描述
完成修改后就可以运行predict.py进行检测了。运行后输入图片路径即可检测。

发表评论

表情:
评论列表 (有 0 条评论,564人围观)

还没有评论,来说两句吧...

相关阅读