矩陣分塊的兩種方法

假設(shè)下圖矩陣,按照紅線切分成 6 個(gè)子矩陣,原矩陣成為分塊矩陣

  • patch size: 2x3
  • rows=3, cols=2

用兩個(gè) for 循環(huán)肯定可以解決問題,但是今天采用兩種新方法。

方法 1:np.lib.stride_tricks.as_strided

import numpy as np

a = np.arange(1, 37).reshape(6, 6)
a = np.lib.stride_tricks.as_strided(
    a,
    shape=(3, 2, 2, 3),  # 要輸出矩陣的 shape
    strides=a.itemsize * np.array([12, 3, 6, 1])
)

print(a)

strides:

  • a.itemsize=8,因?yàn)?a.dtype = int64,表示 8 個(gè)字節(jié)
    后面的 array 告訴函數(shù) 怎么索引原矩陣數(shù)據(jù)組成新矩陣
    從右往左依次是:
  • 1,子矩陣內(nèi) 列與列 相隔的元素?cái)?shù)量,如 1, 2
  • 6,子矩陣內(nèi) 行與行 相隔的元素?cái)?shù)量,如 1, 7
  • 3,子矩陣間 列與列 相隔的元素?cái)?shù)量,如 1, 4
  • 12,子矩陣間 行與行 相隔的元素?cái)?shù)量,如 1, 13

同樣的,可以將此方法拓展到 3D 矩陣,就能方便地將圖片轉(zhuǎn)化成 patches.

import numpy as np

# dummy image
a = np.array([[x, x, x] for x in range(1, 37)]).reshape((6, 6, 3))
a = np.lib.stride_tricks.as_strided(
    a,
    shape=(3, 2, 2, 3, 3),
    strides=a.itemsize * np.array([12 * 3, 3 * 3, 6 * 3, 1 * 3, 1])
)
# cvt batchs = 3x2 = 6
a = a.reshape((-1, 2, 3, 3))
print(a)

注意:

  • 轉(zhuǎn)化子圖,也要以 3×2 的形式,不能在 shape 那里直接指定 batch,可以再加一步 reshape 來指定。
  • strides 這里是 5 維,要記得最里面的元素間隔還是 1,外邊的要 ×3

圖片實(shí)例

import numpy as np
import cv2
import os

a = cv2.imread('aerials/Afghan_2003258.jpg')

img_h, img_w, _ = a.shape  # (1400, 1800, 3)
subimg_h, subimg_w = 700, 900

a = np.lib.stride_tricks.as_strided(
    a,
    shape=(img_h // subimg_h, img_w // subimg_w, subimg_h, subimg_w, 3),  # rows, cols
    strides=a.itemsize * np.array([subimg_h * img_w * 3, subimg_w * 3, img_w * 3, 1 * 3, 1])
)

# cvt batchs
a = a.reshape((-1, subimg_h, subimg_w, 3))

out_dir = 'aerials/split'
for idx, subimg in enumerate(a):
    cv2.imwrite(os.path.join(out_dir, 'Afghan_2003258_%d.jpg' % idx), subimg)
原圖 1400x1800
子圖 700x900

缺點(diǎn):如果原圖 h,w 不能被子圖 h,w 整除,會(huì)丟失右側(cè)和下側(cè)部分?jǐn)?shù)據(jù)
如下圖子圖為 400x400,丟失了右側(cè) 200 列 和 下側(cè) 200 行數(shù)據(jù)。

子圖 400x400

方法 2:reshape + transpose

inspired by ShuffleNet

import numpy as np

a = np.arange(1, 37).reshape(6, 6)
a = a.reshape(3, 2, 2, 3)
a = np.transpose(a, [0, 2, 1, 3])

print(a)

After reshape,原始矩陣是橫著索引的,并不是我們想要的

[[[[ 1  2  3]
   [ 4  5  6]]

  [[ 7  8  9]
   [10 11 12]]]


 [[[13 14 15]
   [16 17 18]]

  [[19 20 21]
   [22 23 24]]]


 [[[25 26 27]
   [28 29 30]]

  [[31 32 33]
   [34 35 36]]]]

After transpose,轉(zhuǎn)換第 2 維 和 第 3 維,就對(duì)了

[[[[ 1  2  3]
   [ 7  8  9]]

  [[ 4  5  6]
   [10 11 12]]]


 [[[13 14 15]
   [19 20 21]]

  [[16 17 18]
   [22 23 24]]]


 [[[25 26 27]
   [31 32 33]]

  [[28 29 30]
   [34 35 36]]]]
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。