TensorFlow代码 https://github.com/eragonruan/text-detection-ctpn
训练 main/train.py
1. utils/prepare/split_label.py
- 缩放图片resize image(长宽 最大1200,最小600)
- label处理
2. 输入
- input_image 原图像 [[1, H, W, 3]]
- bbox(GT) [[x_min, y_min, x_max, y_max, 1], […], …]
- im_info(GT) 图像的高,宽,通道(二维ndarray) [[h,w,c]]
3. 模型 model_train.py -> model()
- 图像去均值 mean_image_subtraction(均值设为means=[123.68, 116.78, 103.94])
- 输入到 VGG16, conv5 -> [N, H/16, W/16, 512]
- conv2d -> [N, H/16, W/16, 512]
- BLSTM -> [N, H/16, W/16, 512]
- FC -> bbox_pred + cls_pred + cls_prob-> [N, H/16, W/16, 410] + [N, H/16, W/16, 2x10] + [N, H/16, W/16, 210]
4. 损失 model_train.py -> loss()
- 生成anchor分类标签和bounding-box回归目标 anchor_target_layer()
- 输入: cls_pred, bbox(GT), im_info(GT)
- 返回: [rpn_labels, rpn_bbox_targets, rpn_bbox_inside_weights, rpn_bbox_outside_weights]
- 方法:
- 生成基本的anchor(10个),每个anchor对应的四个坐标 [x_min, y_min, x_max, y_max] -> heights = [11, 16, 23, 33, 48, 68, 97, 139, 198, 283] widths = [16]
- 生成所有的anchor(H/16xW/16x10): 生成feature-map和真实image上anchor之间的偏移量
- 仅保留那些还在图像内部的anchor,超出图像的都删掉
- rpn_labels 生成标签(>0.7或者最大的为正标签,<0.3的为负标签),限制标签的数量(总共256个) (先给正的上标签还是先给负的上标签?)
- rpn_bbox_targets 根据anchor和gtbox计算得真值(anchor和gtbox之间的偏差)
- 把超出图像范围的anchor再加回来
- 计算分类损失
- rpn_cross_entropy_n = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=rpn_label, logits=rpn_cls_score)
- rpn_cross_entropy = tf.reduce_mean(rpn_cross_entropy_n)
- 计算回归损失
- rpn_loss_box_n = tf.reduce_sum(rpn_bbox_outside_weights * smooth_l1_dist(rpn_bbox_inside_weights * (rpn_bbox_pred - rpn_bbox_targets)), reduction_indices=[1])
- rpn_loss_box = tf.reduce_sum(rpn_loss_box_n) / (tf.reduce_sum(tf.cast(fg_keep, tf.float32)) + 1)
- 计算正则损失
- regularization_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)
- 模型损失
- model_loss = rpn_cross_entropy + rpn_loss_box
- 总损失
- total_loss = tf.add_n(regularization_losses) + model_loss
5. AdamOptimizer() 回归损失
预测 main/demo.py
1. 输入
- input_image [1, H, W, 3]
- input_im_info [[H, W, C]]
2. 缩放图片:600x1200
3. 使用训练好的模型得出 bbox_pred, cls_pred, cls_prob
4. proposal_layer() 生成propsal
- 输入:cls_prob, bbox_pred, im_info
- 返回:textsegs (1 x H x W x A, 5) e.g. [0, x1, y1, x2, y2]
- 方法:
- 生成基本的anchor
- 生成整张图像所有的anchor
- 根据anchor和bbox_pred,做逆变换,得到box在图像上的真实坐标
- 将所有的proposal修建一下,超出图像范围的将会被修剪掉
- 移除高度或宽度小于阈值的proposal
- 根据分数排序所有的proposal, 进行nms
- 输出所有proposal以及分数
5. TextDetector() 文本检测
- 输入: textsegs, score[:, np.newaxis], im_info[:2]
- 输出: 文本行坐标
- 方法:
- 删除得分较低的proposal, 阈值0.7
- 按得分排序
- 对proposal做nms
- 文本行的构建(两种方式:水平矩形框和有角度的矩形框)
- textdetector = TextDetector(DETECT_MODE=‘O’) # DETECT_MODE可以是’O’或者’H’
- 输出[xmin, ymin, xmax, ymin, xmax, ymax, xmin, ymax, score]
疑问以及代码问题:
1. Side-refinement部分的损失函数去哪了
在这个代码里边没有体现
2. rpn_bbox_outside_weights和rpn_bbox_inside_weights用来做什么的
CTPN中只需要回归proposal的y, h,而bbox_pred的输出为x, y, w, h,所以设置inside_weights=[0, 1, 0, 1]只计算y和h的损失; outside_weights来控制哪些样本参与计算回归损失
3. 代码中 split_label.py中46, 47行应为 new_h % 16 == 0
4. 代码中 config.py 中应该为 RPN_BBOX_INSIDE_WEIGHTS = (0.0, 1.0, 0.0, 1.0)