如何只留下图像中最大的斑点?

How to leave only the largest blob in an image?

我有大脑的二值图像。我只想将 blob 留在中心并移除周围的 "noise" 圆形形状。

这是一个示例图片:

我尝试使用 OpenCV 并获取计数,但失败得很惨。我也根本不需要边界矩形框,我只想保留图像中的中心斑点,因为它在我提供的图像中看起来是这样,并删除周围的 noise/circle。这可能吗?

我假设,您想保留实际的大脑 ("blob in the center") 并摆脱头骨 ("noise circular looking shape")。

不幸的是,你没有显示任何代码,所以我不确定你在使用等高线时失败了什么,但这是我的建议:

import cv2
import numpy as np

# Read input
img = cv2.imread('images/t6igVVk.png', cv2.IMREAD_GRAYSCALE)

# Generate intermediate image; use morphological closing to keep parts of the brain together
inter = cv2.morphologyEx(img, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)))

# Find largest contour in intermediate image
cnts, _ = cv2.findContours(inter, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cnt = max(cnts, key=cv2.contourArea)

# Output
out = np.zeros(img.shape, np.uint8)
cv2.drawContours(out, [cnt], -1, 255, cv2.FILLED)
out = cv2.bitwise_and(img, out)

cv2.imshow('img', img)
cv2.imshow('inter', inter)
cv2.imshow('out', out)
cv2.waitKey(0)
cv2.destroyAllWindows()

最终输出 out.png 如下所示:

我对两张图片都做了一些形态学上的关闭(morphologyEx, getStructuringElement) on the input image to keep the actual parts of the brain together. On that intermediate image, I look for the largest contour. In my findContours call, I use theRETR_EXTERNAL mode to only get all "external contours". That means, when later drawing this contour, it'll be also filled in the middle (i.e. the lateral ventricles). So, finally I just use a bitwise_and 来解决这个问题。这也修复了中间图片中太大的部分。

希望对您有所帮助!

通过使用 cv2.morphologyEx,我从二进制图像中丢失了很多细节。我正在使用以下代码来保留图像的最大白色区域 -

import skimage
from skimage import measure

labels_mask = measure.label(input_mask)                       
regions = measure.regionprops(labels_mask)
regions.sort(key=lambda x: x.area, reverse=True)
if len(regions) > 1:
    for rg in regions[1:]:
        labels_mask[rg.coords[:,0], rg.coords[:,1]] = 0
labels_mask[labels_mask!=0] = 1
mask = labels_mask

输入图像:

输出图像: