如何填充孔或减少图像中的噪音?

发布于 2025-01-26 04:50:24 字数 1040 浏览 2 评论 0原文

我需要降低图像中的噪音,例如一个波纹管,即填充白色物体中的孔。我尝试使用OpenCV尝试了一些东西,但最终可以删除对象的一部分。是否有更好的方法可以在不失去对象本身的情况下进行此操作?任何帮助都将受到赞赏!

到目前为止,这是我到目前为止所拥有的

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)

”在此处输入图像描述“

输出图像:

“在此处输入图像说明”

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

×纯※雪 2025-02-02 04:50:24

以下 @jeruluke 的建议,我使用cv.morphologyex(img,cv.morph_close,kernel,kernel),并在以下代码段中获得了我想要的结果。

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)

输出图像:

“在此处输入图像描述”

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:

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文