如何在 Matlab 中将像素分组为 blob?

How to group pixels into blobs in Matlab?

我有这张在深色背景上有白点的图片:

我想将靠近的像素分组为一个斑点。在此图像中,这意味着图像中将有两个斑点,一个用于顶部的像素,一个用于底部的像素。任何不太靠近这两个斑点的像素都必须更改为背景颜色(必须指定一个阈值来选择哪些像素落入斑点,哪些像素太远)。我该怎么做?有什么Matlab函数可以用吗?

要对点进行分组,可以简单地充分平滑图像以将它们模糊在一起。靠近的点(相对于模糊内核大小)将被合并,相距较远的点则不会。

平滑图像的最佳方法是使用 Gaussian filter. MATLAB implements this using the imgaussfilt function since 2015a. For older versions of MATLAB (or Octave, as I'm using here) you can use fspecial and imfilter instead. But you have to be careful because fspecial makes it really easy to create a kernel that is not at all a Gaussian kernel。这就是现在弃用该方法并创建 imgaussfilt 函数的原因。

这是执行此操作的一些代码:

% Load image
img = imread('https://i.stack.imgur.com/NIcb9.png');
img = rgb2gray(img);

% Threshold to get dots
dots = img > 127; % doesn't matter, this case is trivial

% Group dots
% smooth = imgaussfilt(img,10); % This works for newer MATLABs
g = fspecial("gaussian",6*10+1,10);
smooth = imfilter(img,g,'replicate'); % I'm using Octave here, it doesn't yet implement imgaussfilt

% Find an appropriate threshold for dot density
regions = smooth > 80; % A smaller value makes for fewer isolated points

% Dots within regions
newDots = dots & regions;

要识别同一区域内的斑点,只需标记 regions 图像,然后与 dots 图像相乘:

% Label regions
regions = bwlabel(regions);

% Label dots within regions
newDots = regions .* dots;

% Display
imshow(label2rgb(newDots,'jet','k'))