Skip to content
Advertisement

How to Divide an array in to segments and then do sub segments of the segments using python numpy?

I want to do divide an 8*8 array in to 4 segments(each segment of 4*4 array) as shown below in step2. Then again divide each segment in to other small 4 subsegemnts(each subsegment of 2*2 array) and then find the mean of each subsegment and then find the stabbndard deviation of each segment using the 4 means of the 4 subsegments in it. So that finally I only have an array (2*2 array) ie with 1 standard deviation for 1 segment.

import numpy as np
from skimage.util.shape import view_as_blocks

arr=np.array([[1,2,3,4,5,6,7,8],[1,2,3,4,5,6,7,8],[1,2,3,4,5,6,7,8],[1,2,3,4,5,6,7,8],[1,2,3,4,5,6,7,8],[1,2,3,4,5,6,7,8],[1,2,3,4,5,6,7,8],[1,2,3,4,5,6,7,8]])

img= view_as_blocks(arr, block_shape=(4,4))

upto this I have tried but I was unable to go further in my requirement as I am completely new to python and numpy. Kindly, help me in achieve my requirement.

#step1-Array
array([[1, 2, 3, 4, 5, 6, 7, 8],
       [1, 2, 3, 4, 5, 6, 7, 8],
       [1, 2, 3, 4, 5, 6, 7, 8],
       [1, 2, 3, 4, 5, 6, 7, 8],
       [1, 2, 3, 4, 5, 6, 7, 8],
       [1, 2, 3, 4, 5, 6, 7, 8],
       [1, 2, 3, 4, 5, 6, 7, 8],
       [1, 2, 3, 4, 5, 6, 7, 8]])

#step2-segments
array([[[[1, 2, 3, 4],
         [1, 2, 3, 4],
         [1, 2, 3, 4],
         [1, 2, 3, 4]],

        [[5, 6, 7, 8],
         [5, 6, 7, 8],
         [5, 6, 7, 8],
         [5, 6, 7, 8]]],


       [[[1, 2, 3, 4],
         [1, 2, 3, 4],
         [1, 2, 3, 4],
         [1, 2, 3, 4]],

        [[5, 6, 7, 8],
         [5, 6, 7, 8],
         [5, 6, 7, 8],
         [5, 6, 7, 8]]]])

**more steps to go to get final output**

Expected Output

([[1.0, 1.0],
  [1.0, 1.0]])

Advertisement

Answer

It can be done using a function view_as_blocks of skimage.util.shape.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement