'How to fill holes or reduce noise in an image?
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:
Output image:
Solution 1:[1]
Following @JeruLuke's suggestion, I used cv.morphologyEx(img, cv.MORPH_CLOSE, kernel)
and got the result I wanted with the following code snippet.
import cv2
import numpy as np
image = cv2.imread('image.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
kernel_size = (7, 7)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, kernel_size)
closing = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, kernel)
cv2.imwrite('result.png', closing)
Output image:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Davi Magalhães |