简体   繁体   中英

Merging non-overlapping array blocks

I divided a (512x512) 2-dimensional array to 2x2 blocks using this function.

skimage.util.view_as_blocks (arr_in, block_shape)
array([[ 0,  1,  2,  3],
   [ 4,  5,  6,  7],
   [ 8,  9, 10, 11],
   [12, 13, 14, 15]])
   >>> B = view_as_blocks(A, block_shape=(2, 2))
   >>> B[0, 0]
   array([[0, 1],
          [4, 5]])
   >>> B[0, 1]
   array([[2, 3],
          [6, 7]])

Now I need to put the same blocks to their original places after manipulation but I couldn't see any function in skimage for that.

What's the best way to merge the non-overlapping arrays as it was before?

Thank you!

Use transpose/swapaxes to swap the second and third axes and then reshape to have the last two axes merged -

B.transpose(0,2,1,3).reshape(-1,B.shape[1]*B.shape[3])
B.swapaxes(1,2).reshape(-1,B.shape[1]*B.shape[3])

Sample run -

In [41]: A
Out[41]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

In [42]: B = view_as_blocks(A, block_shape=(2, 2))

In [43]: B
Out[43]: 
array([[[[ 0,  1],
         [ 4,  5]],

        [[ 2,  3],
         [ 6,  7]]],


       [[[ 8,  9],
         [12, 13]],

        [[10, 11],
         [14, 15]]]])

In [44]: B.transpose(0,2,1,3).reshape(-1,B.shape[1]*B.shape[3])
Out[44]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

This is where you'd better use einops :

from einops import rearrange

# that's how you could rewrite view_as_blocks
B = rearrange(A, '(x dx) (y dy) -> x y dx dy', dx=2, dy=2)

# that's an answer to your question
A = rearrange(B, 'x y dx dy -> (x dx) (y dy)')

See documentation for more operations on images

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM