代码之家  ›  专栏  ›  技术社区  ›  Jema

如何在MATLAB中屏蔽图像中的多边形?

  •  1
  • Jema  · 技术社区  · 6 年前

    我已经在图像上绘制了一个多边形,现在想对其进行遮罩。我只想看到多边形内部的区域,让外部的一切都是黑色的。

    以下是我在图像上绘制多边形的代码:

    i = imread('Vlc1.1.png');
    pos = [170 350 290 230 430 230 600 350 170 350];
    S = insertShape(i,'Polygon',pos);
    imshow(S);
    

    下面是生成的图像:

    enter image description here

    如何将多边形外的所有内容设置为黑色?

    1 回复  |  直到 6 年前
        1
  •  3
  •   gnovice    6 年前

    最简单的方法是使用 poly2mask 中的函数 Image Processing Toolbox 要从多边形创建二元遮罩,请将图像中遮罩外的所有像素设置为0(即黑色):

    img = imread('Vlc1.1.png');  % Image data, assumed to be 3D RGB image
    pos = [170 350 290 230 430 230 600 350 170 350];  % Pairs of x-y coordinates
    
    bw = ~poly2mask(pos(1:2:end), pos(2:2:end), size(img, 1), size(img, 2));  % 2D mask
    bw = repmat(bw, [1 1 size(img, 3)]);  % Replicate the mask to make it 3D
    maskimg = img;
    maskimg(bw) = 0;
    imshow(maskimg);
    

    使用示例图像的裁剪版本,结果如下:

    enter image description here