具有numpy.reshape()的反向skimage view_as_blocks()

问题描述 投票:0回答:1

我想将具有2通道的4x4图像分成多个不重叠的正方形。

之后,我想重建图像。

from skimage.util import view_as_blocks

# create testM array 
array([[[[0.53258505, 0.31525832, 0.21378392, 0.5019507 ],
         [0.31612498, 0.24320562, 0.93560226, 0.08232264],
         [0.89784454, 0.12741783, 0.88049819, 0.29542855],
         [0.11336386, 0.71023215, 0.45679456, 0.2318959 ]],

        [[0.61038755, 0.74389586, 0.85199794, 0.46680889],
         [0.01701045, 0.93953861, 0.03183684, 0.00740579],
         [0.58878569, 0.71348253, 0.33221104, 0.12276253],
         [0.04026615, 0.53837528, 0.06759152, 0.27477069]]]])

# use view_as_blocks() to get "grid" image
testB = view_as_blocks(testM, block_shape=(1,2,2,2)).reshape(-1,*(1,2,2,2))

现在我有这个大小为2x2的数组的多个块:

array([[[[[0.53258505, 0.31525832],
          [0.31612498, 0.24320562]],

         ...

         [[0.33221104, 0.12276253],
          [0.06759152, 0.27477069]]]]])

但是,我无法将其重塑回原来的形状

testB.reshape(1,2,4,4)

导致此。每个“块”仅在一个值后面附加一个值,但不视为一个块。

array([[[[0.53258505, 0.31525832, 0.31612498, 0.24320562],
         [0.61038755, 0.74389586, 0.01701045, 0.93953861],
         [0.21378392, 0.5019507 , 0.93560226, 0.08232264],
         [0.85199794, 0.46680889, 0.03183684, 0.00740579]],

        [[0.89784454, 0.12741783, 0.11336386, 0.71023215],
         [0.58878569, 0.71348253, 0.04026615, 0.53837528],
         [0.88049819, 0.29542855, 0.45679456, 0.2318959 ],
         [0.33221104, 0.12276253, 0.06759152, 0.27477069]]]])

我在使用.swapaxes()之前尝试了多个reshape(),但无法正常工作。

python numpy multidimensional-array reshape scikit-image
1个回答
0
投票

正在发生的事情是您的.reshape((-1, 1, 2, 2, 2)),即您对块的线性化导致复制:

import numpy as np
from skimage.util import view_as_blocks

arr = np.arange(24).astype(np.uint8).reshape((4, 6))
blocked = view_as_blocks(arr, (2, 3))
blocked_reshaped = blocked.reshape((-1, 2, 3))
print(arr.shape)
print(arr.strides)
print(blocked.shape)
print(blocked.strides)
print(blocked_reshaped.shape)
print(blocked_reshaped.strides)
print(np.may_share_memory(blocked, blocked_reshaped))

结果:

(4, 6)
(6, 1)
(2, 2, 2, 3)
(12, 3, 6, 1)
(4, 2, 3)
(6, 3, 1)
False

跨步是一个线索,表明数组的元素在基础内存中不再处于相同的线性顺序,因此重塑会导致您观察到的怪异转置:

block_reshaped_orig = blocked_reshaped.reshape((4, 6))
print(arr)
print(block_reshaped_orig)

结果:

[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]
 [12 13 14 15 16 17]
 [18 19 20 21 22 23]]
[[ 0  1  2  6  7  8]
 [ 3  4  5  9 10 11]
 [12 13 14 18 19 20]
 [15 16 17 21 22 23]]

我看到两个选项:

  • 如果您可以避免重塑和复制,那么最后的重塑调用将正常工作。
  • 如果您需要对其他正在执行的处理进行重塑,那么具有讽刺意味的是,您可以使用另一个view_as_blocks调用并重塑以恢复原始顺序:
print(
    view_as_blocks(blocked_reshaped_orig, (2, 3)).reshape((4, -1))
)

结果:

[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]
 [12 13 14 15 16 17]
 [18 19 20 21 22 23]]

我希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.