zoukankan      html  css  js  c++  java
  • 可变形卷积 deformable convolution 学习记录

    Deformable ConvNets v1:
    论文地址:https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch
    工程地址:https://github.com/felixlaumon/deform-conv

    论文地址: Deformable ConvNets v2: More Deformable, Better Results
    工程地址:https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch


    这里需要强调一下,N代表kernel_size*kernel_size,并不是通道数

    offset = self.p_conv(x)

    x.shape torch.Size([32,64,28,28])

    offset.shape torch.Size([32,18,28,28])

    这一步输入图片学习偏移量offset,输入的feature map尺寸是(64,28,28)分别表示通道数,h和w。输出之所以是18通道的,是因为kernel size是3,卷积核有33=9个点,每个点都有x偏移量和y偏移量(从这里看得出每个输入通道做同样的偏移处理),18通道的前九个通道表示x偏移量,后9个通道表示y偏移量。然后再经过一次卷积

    对应的看上图下面那个,可以看到原来是方形3
    3的,每个小块再加了一点点偏移,卷积。根据代码,应该是每个channel都用同一个偏移量,原始输入的feature map每个点应该都有一个3*3的滑框,再加上对应的一个18个偏移量。每个点对应的偏移都不一样。

    以下转摘于:https://blog.csdn.net/mykeylock/article/details/77746499
    可变形卷积是指卷积核在每一个元素上额外增加了一个参数方向参数,这样卷积核就能在训练过程中扩展到很大的范围。
    可变形卷积的论文为:Deformable Convolutional Networks【1】
    而之前google一篇论文对这篇论文有指导意义:Spatial Transformer Networks【2】
    论文【1】的github代码地址为https://github.com/felixlaumon/deform-conv
    ——————————————————————————————————————————
    可变形卷积很好理解,但如何实现呢?实现方面需要关注两个限制:
    1、如何将它变成单独的一个层,而不影响别的层;
    2、在前向传播实现可变性卷积中,如何能有效地进行反向传播。
    这两个问题的答案分别是:
    1、在实际操作时,并不是真正地把卷积核进行扩展,而是对卷积前图片的像素重新整合,
    变相地实现卷积核的扩张;
    2、在图片像素整合时,需要对像素进行偏移操作,偏移量的生成会产生浮点数类型,
    而偏移量又必须转换为整形,直接对偏移量取整的话无法进行反向传播,这时采用双线性差值的方式来得到对应的像素。
    ——————————————————————————————————————————
    可变性卷积的流程为:
    1、原始图片batch(大小为bhwc),记为U,经过一个普通卷积,卷积填充为same,即输出输入大小不变,
    对应的输出结果为(b
    hw2c),记为V,输出的结果是指原图片batch中每个像素的偏移量(x偏移与y偏移,因此为2c)。
    2、将U中图片的像素索引值与V相加,得到偏移后的position(即在原始图片U中的坐标值),需要将position值限定为图片大小以内。
    position的大小为(bhw*2c),但position只是一个坐标值,而且还是float类型的,我们需要这些float类型的坐标值获取像素。
    3、例,取一个坐标值(a,b),将其转换为四个整数,floor(a), ceil(a), floor(b), ceil(b),将这四个整数进行整合,
    得到四对坐标(floor(a),floor(b)), ((floor(a),ceil(b)), ((ceil(a),floor(b)), ((ceil(a),ceil(b))。这四对坐标每个坐标都对应U
    中的一个像素值,而我们需要得到(a,b)的像素值,这里采用双线性差值的方式计算
    (一方面得到的像素准确,另一方面可以进行反向传播)。
    4、在得到position的所有像素后,即得到了一个新图片M,将这个新图片M作为输入数据输入到别的层中,如普通卷积。
    ——————————————————————————————————————————

    https://blog.csdn.net/scut_salmon/article/details/97050908
    代码似乎也是按照这个流程写的,不过上面的输出结果不应该是(b*h*w*2c),而是(b*h*w* (2kernel_size*kernel_size)),因为只需要记录可变形卷积滤波器变形之后的位置,
    滤波器的原始尺寸是kernel_size*kernel_size,需记录x坐标和y坐标,故为2*kernel_size*kernel_size
    
    offset = self.p_conv(x)
    #x.shape       torch.Size([32,64,28,28])
    #offset.shape  torch.Size([32,18,28,28])
    
    这一步输入图片学习偏移量offset,输入的feature map尺寸是(64,28,28)分别表示通道数,h和w。输出之所以是18通道的,是因为kernel size是3,卷积核有3*3=9个点,每个点都有x偏移量和y偏移量(从这里看得出每个输入通道做同样的偏移处理),18通道的前九个通道表示x偏移量,后9个通道表示y偏移量。
    
    

    以上是可变性卷积的实现流程,但实际代码实现起来涉及到比较多的tensor操作,比较繁琐。
    代码实现主要的文件有
    cnn.py:采用keras定义了所有训练需要的层,可变形卷积层为ConvOffset2D,
    layer.py:定义了ConvOffset2D可变形卷积类,主要包括keras中需要的call函数与init函数,
    call函数首先调用普通卷积,然后调用deform_conv.py中函数实际计算。
    deform_conv.py:真正实现可变形卷积计算的文件。
    layer.py主要代码:

    def __init__(self, filters, init_normal_stddev=0.01, **kwargs):
     
        self.filters = filters
        super(ConvOffset2D, self).__init__(
            self.filters * 2, (3, 3), padding='same', use_bias=False,
            kernel_initializer=RandomNormal(0, init_normal_stddev),
            **kwargs
        )
    def call(self, x):
        """Return the deformed featured map"""
     
        #获取x大小,x大小为(b,h,w,c),分别为batch_size,图片高度,图片宽度,特征图大小
     
        x_shape = x.get_shape()
     
        #调用普通卷积获得输出,输出结果为(b,h,w,2c)表示图片中每个像素需要偏移的量(x,y)
        offsets = super(ConvOffset2D, self).call(x)
         #reshape一下输出,方便后续操作,(b*c,h,w,2)表示共有b*c个图片,每个图片为h*w大小,每个像素对应2个方向
        # offsets: (b*c, h, w, 2)   
        offsets = self._to_bc_h_w_2(offsets, x_shape)
        #将原始输入也重新reshape一下方便后续操作
        # x: (b*c, h, w)
        x = self._to_bc_h_w(x, x_shape)
        #调用deform_conv.py中的函数根据原始图片与偏移量生成新图片数据。
        # X_offset: (b*c, h, w)
        x_offset = tf_batch_map_offsets(x, offsets)
        # x_offset: (b, h, w, c)
        x_offset = self._to_b_h_w_c(x_offset, x_shape)
        return x_offset
    def compute_output_shape(self, input_shape):
        """Output shape is the same as input shape
        Because this layer does only the deformation part
        """
        return input_shape
    @staticmethod
    def _to_bc_h_w_2(x, x_shape):
        """(b, h, w, 2c) -> (b*c, h, w, 2)"""
        x = tf.transpose(x, [0, 3, 1, 2])
        x = tf.reshape(x, (-1, int(x_shape[1]), int(x_shape[2]), 2))
        return x
    @staticmethod
    def _to_bc_h_w(x, x_shape):
        """(b, h, w, c) -> (b*c, h, w)"""
        x = tf.transpose(x, [0, 3, 1, 2])
        x = tf.reshape(x, (-1, int(x_shape[1]), int(x_shape[2])))
        return x
    @staticmethod
    def _to_b_h_w_c(x, x_shape):
        """(b*c, h, w) -> (b, h, w, c)"""
        x = tf.reshape(
            x, (-1, int(x_shape[3]), int(x_shape[1]), int(x_shape[2]))
        )
        x = tf.transpose(x, [0, 2, 3, 1])
        return x
    

    deform_conv.py主要代码:

    def tf_flatten(a):
        """Flatten tensor"""
        return tf.reshape(a, [-1])每个点都有x偏移量和y偏移量(从这里看得出每个输入通道做同样的偏移处理),18通道的前九个通道表示x偏移量,后9个通道表示y偏移量。
     
    def tf_repeat(a, repeats, axis=0):
        """TensorFlow version of np.repeat for 1D"""
        # https://github.com/tensorflow/tensorflow/issues/8521
        assert len(a.get_shape()) == 1
        a = tf.expand_dims(a, -1)
        a = tf.tile(a, [1, repeats])
        a = tf_flatten(a)
        return a
    def tf_repeat_2d(a, repeats):
        """Tensorflow version of np.repeat for 2D"""
        assert len(a.get_shape()) == 2
        a = tf.expand_dims(a, 0)
        a = tf.tile(a, [repeats, 1, 1])
        return a
    def tf_map_coordinates(input, coords, order=1):
        """Tensorflow verion of scipy.ndimage.map_coordinates
        Note that coords is transposed and only 2D is supported
        Parameters
        ----------
        input : tf.Tensor. shape = (s, s)
        coords : tf.Tensor. shape = (n_points, 2)
        """
        assert order == 1
        coords_lt = tf.cast(tf.floor(coords), 'int32')
        coords_rb = tf.cast(tf.ceil(coords), 'int32')
        coords_lb = tf.stack([coords_lt[:, 0], coords_rb[:, 1]], axis=1)
        coords_rt = tf.stack([coords_rb[:, 0], coords_lt[:, 1]], axis=1)
     
        vals_lt = tf.gather_nd(input, coords_lt)
        vals_rb = tf.gather_nd(input, coords_rb)
        vals_lb = tf.gather_nd(input, coords_lb)
        vals_rt = tf.gather_nd(input, coords_rt)
     
     
        coords_offset_lt = coords - tf.cast(coords_lt, 'float32')
        vals_t = vals_lt + (vals_rt - vals_lt) * coords_offset_lt[:, 0]
        vals_b = vals_lb + (vals_rb - vals_lb) * coords_offset_lt[:, 0]
        mapped_vals = vals_t + (vals_b - vals_t) * coords_offset_lt[:, 1]
        return mapped_vals
    def sp_batch_map_coordinates(inputs, coords):
        """Reference implementation for batch_map_coordinates"""
        coords = coords.clip(0, inputs.shape[1] - 1)
        mapped_vals = np.array([
            sp_map_coordinates(input, coord.T, mode='nearest', order=1)
            for input, coord in zip(inputs, coords)
        ])
        return mapped_vals
    def tf_batch_map_coordinates(input, coords, order=1):
        """Batch version of tf_map_coordinates
        Only supports 2D feature maps
        Parameters
        ----------
        input : tf.Tensor. shape = (b, s, s)
        coords : tf.Tensor. shape = (b, n_points, 2)
        Returns
        -------
        tf.Tensor. shape = (b, s, s)
        """
        input_shape = tf.shape(input)
        batch_size = input_shape[0]
        input_size = input_shape[1]
        n_coords = tf.shape(coords)[1]
        coords = tf.clip_by_value(coords, 0, tf.cast(input_size, 'float32') - 1)
     
        #得到目标坐标左上角(left top)的整数坐标
        coords_lt = tf.cast(tf.floor(coords), 'int32')
     
        #得到又下角的整数坐标
        coords_rb = tf.cast(tf.ceil(coords), 'int32')
     
        #得到左下角的整数坐标
        coords_lb = tf.stack([coords_lt[..., 0], coords_rb[..., 1]], axis=-1)
     
        #得到右上角的整数坐标
        coords_rt = tf.stack([coords_rb[..., 0], coords_lt[..., 1]], axis=-1)
     
        #idx为索引展开,idx大小为(b*c*h*w),形如(0,0,0,0,0,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3)
     
        #b*c为5,h*w为4,总数为所有图片所有坐标总数
     
        idx = tf_repeat(tf.range(batch_size), n_coords)
        def _get_vals_by_coords(input, coords):
     
            #stack完后,每一个点表示一个坐标
     
            #形如
     
            #(0,0,0,0,0,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3)
     
            # (3,2,1,2,3,1,2,3,0,0,0,3,2,1,1,2,3,2,0,0,2)
     
                # (3,2,1,0,0,2,0,3,1,2,3,0,0,2,3,0,1,2,0,2,3)
     
            indices = tf.stack([
                idx, tf_flatten(coords[..., 0]), tf_flatten(coords[..., 1])
            ], axis=-1)
            vals = tf.gather_nd(input, indices)
            vals = tf.reshape(vals, (batch_size, n_coords))
            return vals
         #以下为分别得到左上,左下,右上,右下四个点的像素值。
        vals_lt = _get_vals_by_coords(input, coords_lt)
        vals_rb = _get_vals_by_coords(input, coords_rb)
        vals_lb = _get_vals_by_coords(input, coords_lb)
        vals_rt = _get_vals_by_coords(input, coords_rt)
         #用双线性插值得到像素值。
        coords_offset_lt = coords - tf.cast(coords_lt, 'float32')
        vals_t = vals_lt + (vals_rt - vals_lt) * coords_offset_lt[..., 0]
        vals_b = vals_lb + (vals_rb - vals_lb) * coords_offset_lt[..., 0]
        mapped_vals = vals_t + (vals_b - vals_t) * coords_offset_lt[..., 1]
        return mapped_vals
    def sp_batch_map_offsets(input, offsets):
        """Reference implementation for tf_batch_map_offsets"""
        batch_size = input.shape[0]
        input_size = input.shape[1]
        #生成grid,grid表示将一个图片的所有坐标变成两列,每一行两个元素表示x,y
     
        (grid的最后大小为(b*c,h*w,2)
        offsets = offsets.reshape(batch_size, -1, 2)
        grid = np.stack(np.mgrid[:input_size, :input_size], -1).reshape(-1, 2)
        grid = np.repeat([grid], batch_size, axis=0)
     
        #将原始坐标与坐标偏移量相加,得到目标坐标,coords的大小为(b*c,h*w,2)
        coords = offsets + grid
     
        #目标坐标需要在图片最大坐标范围内,将目标坐标进行切割限制
        coords = coords.clip(0, input_size - 1)
        #根据原始输入与目标坐标得到像素。
        mapped_vals = sp_batch_map_coordinates(input, coords)
        return mapped_vals
    def tf_batch_map_offsets(input, offsets, order=1):
        """Batch map offsets into input
        Parameters
        ---------
        input : tf.Tensor. shape = (b, s, s)
        offsets: tf.Tensor. shape = (b, s, s, 2)
        Returns
        -------
        tf.Tensor. shape = (b, s, s)
        """
        input_shape = tf.shape(input)
        batch_size = input_shape[0]
        input_size = input_shape[1]
        offsets = tf.reshape(offsets, (batch_size, -1, 2))
        grid = tf.meshgrid(
            tf.range(input_size), tf.range(input_size), indexing='ij'
        )
        grid = tf.stack(grid, axis=-1)
        grid = tf.cast(grid, 'float32')
        grid = tf.reshape(grid, (-1, 2))
        grid = tf_repeat_2d(grid, batch_size)
        coords = offsets + grid
        mapped_vals = tf_batch_map_coordinates(input, coords)
        return mapped_vals
    
  • 相关阅读:
    团队-科学计算器-成员简介及分工
    提交错误
    《结对-结对编项目作业名称-需求分析》
    对软件工程课程的期望
    自我介绍
    课堂作业0
    selenium+Java刷新浏览器
    不要焦虑~~
    JAVA代码实现得到指定文件夹下的文件名
    安全检测检查清单(IOS版APP)
  • 原文地址:https://www.cnblogs.com/yanghailin/p/12321832.html
Copyright © 2011-2022 走看看