Search code examples
pythonnumpyscipyndimage

How can I make z axis optional in np.arrays? (Error: footprint array has incorrect shape)


I was trying to figure out how to make "z" axis optional for 2D and 3D inputs without "if" condition if it is possible. So, if the input is 2D, it will ignore z axis. If input is 3D, it will need z value. Any help or suggestion would be appreciated.

def grey_closing(matrix, x=2, y=2, z=1):
    matrix = ndimage.grey_opening(matrix, structure=np.ones((x,y,z)))
    return matrix

test_result_aug_2 = grey_closing(test_result_aug_2)

This is the error that I get:

RuntimeError                              Traceback (most recent call last)
<ipython-input-249-3772fbf0cb7c> in <module>()
----> 1 test_result_aug_2 = grey_closing(test_result_aug_2)
      2 test_result2 = grey_closing(test_result2)
      3 plot_comparison(test_result2, test_result_aug_2)

<ipython-input-241-2b0072643ca3> in grey_closing(matrix, x, y, z)
     35     return matrix
     36 def grey_closing(matrix, x=2, y=2, z=1):
---> 37     matrix = ndimage.grey_closing(matrix, structure=np.ones((x,y,z)))
     38     return matrix

c:\python36\lib\site-packages\scipy\ndimage\morphology.py in grey_closing(input, size, footprint, structure, output, mode, cval, origin)
   1520         warnings.warn("ignoring size because footprint is set", UserWarning, stacklevel=2)
   1521     tmp = grey_dilation(input, size, footprint, structure, None, mode,
-> 1522                         cval, origin)
   1523     return grey_erosion(tmp, size, footprint, structure, output, mode,
   1524                         cval, origin)

c:\python36\lib\site-packages\scipy\ndimage\morphology.py in grey_dilation(input, size, footprint, structure, output, mode, cval, origin)
   1356 
   1357     return filters._min_or_max_filter(input, size, footprint, structure,
-> 1358                                       output, mode, cval, origin, 0)
   1359 
   1360 

c:\python36\lib\site-packages\scipy\ndimage\filters.py in _min_or_max_filter(input, size, footprint, structure, output, mode, cval, origin, minimum)
   1001         fshape = [ii for ii in footprint.shape if ii > 0]
   1002         if len(fshape) != input.ndim:
-> 1003             raise RuntimeError('footprint array has incorrect shape.')
   1004         for origin, lenf in zip(origins, fshape):
   1005             if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf):

RuntimeError: footprint array has incorrect shape.

Solution

  • Maybe:

    structure_shape = (x, y, z)[:matrix.ndim]
    structure = np.ones(structure_shape)
    

    so z is ignored if matrix is 2D