Matlab - 如何使用 imfill 填充图像的一部分?

Matlab - How to fill part of an image using imfill?

我有这样一张图片:

img

我想使用像这样的掩码作为种子点的位置来填充底部:

面具

这是我试过但没有用的方法:

img = imread('img.jpg'); maskImg = imread('mask.png');
[Gmag, Gdir] = imgradient(img,'sobel');
mask = imbinarize(maskImg);
[rows,columns] = find(mask);
bw = imfill(Gmag, [rows(:) columns(:)]);
figure, imshow(bw);

错误信息是:

Function IMFILL expected input number 2, CONN, to be a valid connectivity specifier. A nonscalar connectivity specifier must be 3-by-3-by- ... -by-3.

如何填充上图中的道路部分?

对于各种图像来说不是很好,也不是高度可重现的,但也许可以从这些基本图像处理技术的混乱中提取一些有趣的东西。

Image = imread("img.jpg");
Mask = imread("mask.png");
Contrast_Stretched_Image = imadjust(Image,stretchlim(Image),[]);
Max_Filtered_Image = ordfilt2(Contrast_Stretched_Image,1,ones(9,9));
Filtered_Image = medfilt2(Max_Filtered_Image, [15 15]);
Filtered_Image = Filtered_Image > 200;
[Boundaries,Boundary_Image] = bwboundaries(Filtered_Image, 'noholes');
Largest_Boundary = Boundaries(1);
Largest_Boundary = Largest_Boundary{1,1};

imshow(Boundary_Image)
[Image_Height,Image_Width] = size(Image);
Binary_Image = zeros(Image_Height,Image_Width);
for Boundary_Index = 1: length(Largest_Boundary)

    X = Largest_Boundary(Boundary_Index,1);
    Y = Largest_Boundary(Boundary_Index,2);
    Binary_Image(X,Y) = 255;

end

Filled_Binary_Image = logical(imfill(Binary_Image,'holes'));
imshow(Filled_Binary_Image);
Image_Fill = uint8(~Filled_Binary_Image).*Image;
imshow(Image_Fill);
Mask_Fill = uint8(Filled_Binary_Image).*Mask;
imshow(Image_Fill+Mask_Fill);

黑色未遮罩部分的颜色可以在之前或之后更改。可以使用补充语句来改变白色和黑色区域。

四种组合

Image = imread("img.jpg");
Mask = imread("Mask.png");
Mask = (Mask ~= 0);
Image(Mask) = 255;
imshow(Image);

填充白色部分

Image = imread("img.jpg");
Mask = imread("Mask.png");
Mask = uint8(Mask > 0);
Masked_Image = Image.*Mask;
imshow(Masked_Image);

黑色部分填充

Image = imread("img.jpg");
Mask = imread("Mask.png");
Mask = uint8(Mask == 0);
Masked_Image_2 = Image.*Mask;
imshow(Masked_Image_2);

Image = imread("img.jpg");
Mask = imread("Mask.png");
Mask = (Mask == 0);
Image(Mask) = 255;
imshow(Image);

使用MATLAB版本:R2019b