Home > Software engineering >  How to fill holes or reduce noise in an image?
How to fill holes or reduce noise in an image?

Time:05-08

I need to reduce the noise in images like the one bellow, i.e. fill the holes in the white object. I tried something with opencv but it ended up removing part of the object as you can see. Is there a better way to do this without losing the object itself? Any help is appreciated!

Here's what I have so far:

import numpy as np
import cv2

def remove_noise(gray, num):
    Y, X = gray.shape
    nearest_neigbours = [[
        np.argmax(
            np.bincount(
                gray[max(i - num, 0):min(i   num, Y), max(j - num, 0):min(j   num, X)].ravel()))
        for j in range(X)] for i in range(Y)]
    result = np.array(nearest_neigbours, dtype=np.uint8)
    cv2.imwrite('result.png', result)
    return result

img = cv2.imread('img.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

remove_noise(gray, 10)

Input image:

enter image description here

Output image:

enter image description here

CodePudding user response:

Following enter image description here

  • Related