Search code examples
pythonnumpyscikit-imagecontiguous

RuntimeWarning: Cannot provide views on a non-contiguous input array without copying


when using skimage I get the following error:

win = skimage.util.view_as_windows(x, windowSize, windowShift)

C:\Program Files\Anaconda2\lib\site-packages\skimage\util\shape.py:247: RuntimeWarning: Cannot provide views on a non-contiguous input array without copying.
  warn(RuntimeWarning("Cannot provide views on a non-contiguous input "

as far I understood this is because x is a non contiguous array.

I think I solved the problem adding in my code np.ascontiguousarray as below:

win = skimage.util.view_as_windows(np.ascontiguousarray(x), windowSize, windowShift)

Is this the right thing to do? Note: I do it all the time I call this function from skimage...does it have any particular implication?


Solution

  • In [44]: from scipy.io import loadmat
    In [45]: d = loadmat('test7.mat')
    In [46]: d
    Out[46]: 
    {'__globals__': [],
     '__header__': b'MATLAB 5.0 MAT-file, written by Octave 4.0.0, 2016-09-01 15:43:02 UTC',
     '__version__': '1.0',
     'x': array([[ 1.,  2.,  3.],
            [ 4.,  5.,  6.]])}
    
    In [48]: np.info(d['x'])
    class:  ndarray
    shape:  (2, 3)
    strides:  (8, 16)
    itemsize:  8
    aligned:  True
    contiguous:  False
    fortran:  True
    data pointer: 0xabfa13d8
    byteorder:  little
    byteswap:  False
    type: float64
    In [49]: 
    

    or the FLAGS attribute:

    In [52]: x.flags
    Out[52]: 
      C_CONTIGUOUS : False
      F_CONTIGUOUS : True
      OWNDATA : False
      WRITEABLE : True
      ALIGNED : True
      UPDATEIFCOPY : False
    In [54]: d['x'].flags['C_CONTIGUOUS']
    Out[54]: False
    In [55]: d['x'].flags['F_CONTIGUOUS']
    Out[55]: True
    

    np.ascontiguous just does

    array(a, dtype, copy=False, order='C', ndmin=1)
    

    It only does a copy (of the databuffer) if needed to get the right order. See the np.array docs for more details. x.copy() would make a copy regardless.

    An ascontiguous call for all loadmat arrays makes sense if you are going to use them in skimage code that expects C contiguous arrays. view_as_windows is probably doing some sort of a striding tricks to make a (sliding) window.