Jema
Jema

Reputation: 75

How can I mask a polygon in an image in MATLAB?

I have drawn a polygon on an image and now want to mask it. I just want to see the region inside the polygon and have everything outside be black.

Here is my code for drawing the polygon on the image:

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

And here's the resulting image:

enter image description here

How can I set everything outside the polygon to black?

Upvotes: 1

Views: 1542

Answers (1)

gnovice
gnovice

Reputation: 125854

The easiest way to do this would be to use the poly2mask function in the Image Processing Toolbox to create a binary mask from your polygon, then set all the pixels outside that mask to 0 (i.e. black) in your image:

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);

And using a cropped version of your sample image, here's the result:

enter image description here

Upvotes: 3

Related Questions