你可以试试roipoly。
在 SO here 上有一个示例。
这是一个例子:
img = imread('peppers.jpg'); % loads the image we want to use
[BW,xi,yi] = roipoly(img); % create a polynomial surrounding region
BW = repmat(uint8(BW),[1,1,3]); % create mask
selIMG = img.*BW; % apply mask to retain roi and set all else to 0
imview(selIMG)
se=strel('disk',3);
erosion=imerode(selIMG,se);
result_image=imsubtract(selIMG,erosion);
imview(result_image)
编辑
侵蚀:正如 matlab 文档 explains,imerode 从周围像素中选择最小值(imdilate 则相反)。这意味着我的答案中的原始处理不适用于imerode,最好将选择之外的像素设置为色阶上的最大值,我在这里提供了一个关于如何“手动”执行此操作的示例:
img = imread('peppers.jpg'); % loads the image we want to use
[BW,xi,yi] = roipoly(img); % logical mask which contains pixels of interest
nBW = uint8(~BW); % inverse of logical mask to pick surrounding pixels
surroundingMaxedOut = repmat(255*nBW,[1,1,3]); % set surrounding pixels to max value
nBW = repmat(nBW,[1,1,3]); % make mask with 3 channels to pick surrounding pixels
BW = repmat(uint8(BW),[1,1,3]); % make mask with 3 channels to handle RGB
selIMG = img.*BW; % pick the image region of interest
selIMG = selIMG + surroundingMaxedOut; % final selection with surrounding pixels maxed out
imview(selIMG) % inspect the selection
se=strel('disk',3);
erosion=imerode(selIMG,se); % apply erosion
finalIMG = img.*nBW + BW.*erosion; % insert eroded selection into the original image
imview(finalIMG)
正如其他答案所示,matlab 具有隐式处理这些操作的例程,并且不仅在内存管理方面更高效,但是这个示例为您提供了更多控制,因此您可以看到正在发生的事情。