Fill in missing values with nearest neighbour in Python numpy masked arrays?

后端 未结 3 1544
不思量自难忘°
不思量自难忘° 2021-02-02 16:28

I am working with a 2D Numpy masked_array in Python. I need to change the data values in the masked area such that they equal the nearest unmasked value.

NB. If there ar

3条回答
  •  星月不相逢
    2021-02-02 17:03

    I generally use a distance transform, as wisely suggested by Juh_ in this question.

    This does not directly apply to masked arrays, but I do not think it will be that hard to transpose there, and it is quite efficient, I've had no problem applying it to large 100MPix images.

    Copying the relevant method there for reference :

    import numpy as np
    from scipy import ndimage as nd
    
    def fill(data, invalid=None):
        """
        Replace the value of invalid 'data' cells (indicated by 'invalid') 
        by the value of the nearest valid data cell
    
        Input:
            data:    numpy array of any dimension
            invalid: a binary array of same shape as 'data'. True cells set where data
                     value should be replaced.
                     If None (default), use: invalid  = np.isnan(data)
    
        Output: 
            Return a filled array. 
        """
        #import numpy as np
        #import scipy.ndimage as nd
    
        if invalid is None: invalid = np.isnan(data)
    
        ind = nd.distance_transform_edt(invalid, return_distances=False, return_indices=True)
        return data[tuple(ind)]
    

提交回复
热议问题