cv算法岗需要知道的代码实现

文章目录

  • NMS代码实现
  • 基于im2col的展开Python实现卷积层和池化层


NMS代码实现

import numpy as np
bboxes = np.array([[100, 100, 210, 210, 0.72],
                   [250, 250, 420, 420, 0.8],
                   [220, 220, 320, 330, 0.92],
                   [100, 100, 210, 210, 0.72],
                   [230, 240, 325, 330, 0.81],
                   [220, 230, 315, 340, 0.9]])

# 进行非极大值抑制
def nms(iou_thresh=0.5, conf_thr = 0.5):
 # 基本思路:
    # (1) 将置信度进行降序排序,然后选择置信度最大的bbox,将其保存下来
    # (2) 将置信度最大的bbox和其他剩余的bbox进行交并比计算,将交并比大于阈值的bbox从这个集合中剔除出去
    # (3) 如果这个集合不为空的话,我们就重复上面的计算
    # 为了提高效率,我们保留bbox不动,最终保留的也都是bbox在原集合中的索引
    x1, x2, y1, y2, confidence = bboxes[:,0], bboxes[:,1], bboxes[:,2], bboxes[:,3], bboxes[:,4]
    # area
    area = (x1-x2)*(y1-y2)
    index = confidence.argsort()[::-1]
    # print(index)
    keep = []
    while (len(index)) > 0:
        idx_self, idx_other = index[0], index[1:]
        # 如果置信度小于阈值的话,那么后面的bbox就都不符合要求了,直接退出就行了
        if confidence[idx_self] < conf_thr:
            break
        keep.append(idx_self)
        # 计算IOU,注意这里x,y坐标分别是向下和向右
        xx1, yy1 = np.maximum(x1[idx_self], x1[idx_other]), np.maximum(y1[idx_self], y1[idx_other]) 
        xx2, yy2 = np.minimum(x2[idx_self], x2[idx_other]), np.maximum(y2[idx_self], y2[idx_other])
        w, h = np.maximum(0, xx2-xx1), np.maximum(0, yy2-yy1)
        insection = w * h
        union = area[idx_self] + area[idx_other] - insection
        iou = insection / union
        # print(iou)
        # print(np.where(iou <= iou_thresh))
        keep_index = np.where(iou <= iou_thresh)[0] #因为会输出一个tuple数组,前面存储数,后面存储数据类型,所以取[0]
        # print(keep_index)
        index = index[keep_index + 1] #因为去掉了保留的第一个,索引整体加一
    return np.array(keep)

if __name__ == '__main__':
    print(nms())


基于im2col的展开Python实现卷积层和池化层

你可能感兴趣的:(深度学习基础知识,算法,python,开发语言)