高維度時np.transpose與np.reshape的用法

今天遇到一個數組按照排布規律轉變爲4個數組的方法,通過轉置與重塑在高維度實現,源代碼如下:

def downsample_subpixel_new(x,downscale=2):
    [b, h, w, c] = x.get_shape().as_list()
    s = downscale
    if h%s != 0 or w%s != 0:
        print('!!!!Notice: the image size can not be downscaled by current scale')
        exit()
    x_1 = tf.transpose(x, [0, 3, 1, 2])
    x_2 = tf.reshape(x_1, [b, c, h, w // s, s])
    x_3 = tf.reshape(x_2, [b, c, h // s, s, w // s, s])
    x_4 = tf.transpose(x_3, [0, 1, 2, 4, 3, 5])
    x_5 = tf.reshape(x_4, [b, c, h // s, w // s, s * s])
    x_6 = tf.transpose(x_5, [0, 2, 3, 1, 4])
    x_output = tf.reshape(x_6, [b, h // s, w // s, s * s * c])
    return x_output

上面代碼實現的效果爲下圖左邊一個數組變爲右邊四個數組:


其中transpose爲轉置,數組相應維度進行交換

reshape重塑數組形狀,從最後數組一維開始重塑,當維度較小時容易理解,維度超過三維時以下面例子直觀展示:

爲便於觀察,假設開始時數組a爲1到16的數字組成的維度爲[1,4,4,1]的數組

>>> a=np.array([[[[1],[2],[3],[4]],[[5],[6],[7],[8]],[[9],[10],[11],[12]],[[13],[14],[15],[16]]]])
>>> a
array([[[[ 1],
         [ 2],
         [ 3],
         [ 4]],

        [[ 5],
         [ 6],
         [ 7],
         [ 8]],

        [[ 9],
         [10],
         [11],
         [12]],

        [[13],
         [14],
         [15],
         [16]]]])
>>> a.shape
(1, 4, 4, 1)
>>> a1=np.transpose(a,[0,3,1,2])
>>> a1
array([[[[ 1,  2,  3,  4],
         [ 5,  6,  7,  8],
         [ 9, 10, 11, 12],
         [13, 14, 15, 16]]]])
>>> a2=np.reshape(a1,[1,1,4,2,2])
>>> a2
array([[[[[ 1,  2],
          [ 3,  4]],

         [[ 5,  6],
          [ 7,  8]],

         [[ 9, 10],
          [11, 12]],

         [[13, 14],
          [15, 16]]]]])
>>> a3=np.reshape(a2,[1,1,2,2,2,2])
>>> a3
array([[[[[[ 1,  2],
           [ 3,  4]],

          [[ 5,  6],
           [ 7,  8]]],


         [[[ 9, 10],
           [11, 12]],

          [[13, 14],
           [15, 16]]]]]])
>>> a4=np.transpose(a3,[0,1,2,4,3,5])
>>> a4
array([[[[[[ 1,  2],
           [ 5,  6]],

          [[ 3,  4],
           [ 7,  8]]],


         [[[ 9, 10],
           [13, 14]],

          [[11, 12],
           [15, 16]]]]]])
>>> a5=np.reshape(a4,[1,1,2,2,4])
>>> a5
array([[[[[ 1,  2,  5,  6],
          [ 3,  4,  7,  8]],

         [[ 9, 10, 13, 14],
          [11, 12, 15, 16]]]]])
>>> a6=np.transpose(a5,[0,2,3,1,4])
>>> a6
array([[[[[ 1,  2,  5,  6]],

         [[ 3,  4,  7,  8]]],


        [[[ 9, 10, 13, 14]],

         [[11, 12, 15, 16]]]]])
>>> a7=np.reshape(a6,[1,2,2,4])
>>> a7
array([[[[ 1,  2,  5,  6],
         [ 3,  4,  7,  8]],

        [[ 9, 10, 13, 14],
         [11, 12, 15, 16]]]])
可以看到a7數組已經完成了規律的下采樣,其中1,3,9,11座標的像素對應右圖第一個數組
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章