Search code examples
pythonarraysnumpyreplacenoise-reduction

Find and replace subarray in python array


I have a 6600X5100 numpy array which represents a black & white image. I want to clear this image from black pixels noise- remove all black pixle lines (vertically and horizontally) that are shorter than 2 pixels.

So if I have something like this:

[0,  0,  0,   0,   0, 255]
[0, 255,255, 255, 255, 0 ]
[0, 255,255, 255,  0,  0 ]
[0, 255,255 ,255,  0, 255]
[0, 255,255, 255,  0, 255]
[0,  0,  0,   0,   0,  0 ]

The output array will be like this:

[0,  0,  0,   0,   0,  0 ]
[0, 255,255, 255,  0 , 0 ]
[0, 255,255, 255,  0,  0 ]
[0, 255,255 ,255,  0,  0 ]
[0, 255,255, 255,  0,  0 ]
[0,  0,  0,   0,   0,  0 ]

Performance is critical here so a simple loop over the array won't do. Is there a way to quickly find and replace subarray inside an array? So if [0, 255, 255, 0] or [0, 255, 0] is in the image array, replace those parts with 0.

Or if you have a better solution for this task, I will be grateful.


Solution

  • You may want to look at the morphological filters of scikit-image.

    You can define simple filters and use the opening function to clean up the image. You will have to play with the filters to get them exactly as you need them, but the library is very fast.

    import numpy as np
    from skimage.morphology import opening
    
    img = np.array([[0,  0,  0,   0,   0, 255],
                    [0, 255,255, 255, 255, 0 ],
                    [0, 255,255, 255,  0,  0 ],
                    [0, 255,255 ,255,  0, 255],
                    [0, 255,255, 255,  0, 255],
                    [0,  0,  0,   0,   0,  0 ]])
    
    
    # horizontal and vertical filters
    hf = np.array([[0,0,0,0,0],
                   [0,1,1,1,0],
                   [0,0,0,0,0]])
    vf = hf.T
    
    # apply each filter in turn
    out = opening(opening(img, hf),vf)
    
    out
    # returns:
    array([[  0,   0,   0,   0,   0,   0],
           [  0, 255, 255, 255,   0,   0],
           [  0, 255, 255, 255,   0,   0],
           [  0, 255, 255, 255,   0,   0],
           [  0, 255, 255, 255,   0,   0],
           [  0,   0,   0,   0,   0,   0]])