Hi,
I understand that you have the vertices and faces of a figure (likely a head), and you'd like to create an image mask such that all pixels outside the polygonal boundary are set to NaN in the image matrix. You've tried two approaches based on suggestions from the MATLAB community but are facing alignment issues and incorrect masking.
I assume that the figure lies in 2D (or can be projected to 2D), and you are trying to mask a grayscale image based on the polygon defined by the vertices.
In order to mask all areas outside the polygon and set them to NaN, you can follow the below steps:
Step 1: Create a binary mask from the polygon
Use the "poly2mask" function to generate a mask from the x and y coordinates of the polygon:
% Assuming 'vertices' is an Nx2 matrix [x, y] and 'image' is the original image
mask = poly2mask(vertices(:,1), vertices(:,2), size(image,1), size(image,2));
This will create a logical mask where true represents the inside of the polygon.
Step 2: Apply the mask to the image
Convert areas outside the polygon to NaN:
maskedImage = double(image); % convert to double to support NaN
maskedImage(~mask) = NaN;
Note: Using double is important because NaN cannot be assigned to integer-type arrays.
Step 3: Save the masked image
You can save the resulting image matrix using:
save('maskedImage.mat', 'maskedImage');
Optional: Visual check
To verify if the mask aligns correctly, overlay it:
imshow(maskedImage, []);
hold on;
plot(vertices(:,1), vertices(:,2), 'r-', 'LineWidth', 1.5);
This lets you confirm there is no shift between the polygon and the actual image content.
Refer to the documentation of:
- "poly2mask": https://www.mathworks.com/help/images/ref/poly2mask.html
- "imshow": https://www.mathworks.com/help/images/ref/imshow.html
Hope this helps!