'How to revert (re-pack) view_as_block for 3D volume arrays?
I have used view_as_block to split my volumes to 64x64x64 volumes by using http://scikit-image.org/docs/dev/api/skimage.util.html#skimage.util.view_as_blocks. After some filters and modifications, I would like to pack them back. Is there any way to pack them in correct order.
previous shape:
print(np.asarray(padded_training_array).shape)
output:
(2240, 576, 1024, 1)
padded_training_array = view_as_blocks(np.squeeze(padded_training_array[:, :, :], block_shape=(64,64,64))
new shape:
(35, 9, 16, 64, 64, 64)
Some modifications.. and desired shape:
(2240, 576, 1024)
Solution 1:[1]
You can use numpy.reshape
:
>>> import numpy as np
>>> from skimage import util
>>> image = np.random.random((6, 6, 6))
>>> blocks = util.view_as_blocks(image, (2, 2, 2))
>>> blocks.shape
(3, 3, 3, 2, 2, 2)
>>> blocks[(0,) * 6] = 3.0
>>> image2 = np.reshape(blocks, (6, 6, 6))
>>> image2[0, 0, 0]
3.0
But, note that view_as_blocks
returns a view. If your modifications are done in-place, then you don't even need to reshape, your original image will be modified already:
>>> image[0, 0, 0]
3.0
If you want to avoid this, use view_as_blocks(...).copy()
.
Solution 2:[2]
To revert from view_as_blocks to the original 3-dimensional array, the axes list for np.transpose is [0, 3, 1, 4, 2, 5].
from skimage.util import view_as_blocks
import numpy as np
a = np.random.randint(5, size=(64, 128, 32))
a_blocks = view_as_blocks(a, (4, 4, 4))
a_reshaped = a_blocks.transpose([0, 3, 1, 4, 2, 5]).reshape((64, 128, 32))
np.array_equal(a_reshaped, a)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Juan |
Solution 2 | dhmallon |