将 2-D numpy 数组切成较小正方形的 pythonic 方法



我正在尝试使用 numpy 处理 RAW 图像。

打印原始图像 numpy 数组将返回以下内容:

[[372 387 247 ... 560 359 364]
[380 392 243 ... 599 342 356]
[236 238 358 ... 355 600 564]
...
[547 553 344 ...  74  69  69]
[349 328 560 ...  68  74  73]
[341 334 537 ...  70  71  73]]

与形状4384, 5632.

我想获取一个列表列表(2D 列表(,这样每个条目将对应于 2d numpy 数组的8 * 8平方。

这将指示4384/8 , 5632/8的维度列表。

目前我只能想到使用 while 循环并将每个方块附加到列表中,但我认为一定有更好的方法。

有没有一种更pythonic的方法,也许使用列表理解和切片?

请在下面找到答案的简短解释

# 1.  Reshape Image as (height/8, 8, width/8,8)
print(rawimg.reshape(rawimg.shape[0]//8, 8, -1, 8).shape)
# 2. Swap 1 and 2nd index
print(rawimg.reshape(rawimg.shape[0]//8, 8, -1, 8).swapaxes(1,2).shape)
# 3. Reshape again (-1,8,8) with -1 being combined both (548*704) arrays of shape 8x8
print(rawimg.reshape(rawimg.shape[0]//8, 8, -1, 8).swapaxes(1,2).reshape(-1,8,8).shape)

(548, 8, 704, 8)
(548, 704, 8, 8)
(385792, 8, 8)

最新更新