How to create a rectangular mask based on current code for making an elliptical mask
Show older comments
I have an code that creates an elliptical mask and rotates it to a certain angle:
for k = 0:180/deltaK:180-1 % Loop to Rotate the mask in steps.
if rectMask == 0
% Create circular mask.
x = ones(round(diamMax+0.5),1)*(1:round(diamMax+0.5))-round(diamMax+0.5)/2; % Distance in x-direction to centre.
y = (1:round(diamMax+0.5))'*ones(1,round(diamMax+0.5))-round(diamMax+0.5)/2; % Distance in y-direction to centre.
r = sqrt(x.^2+y.^2); % Absolute distance to centre.
maskMax = double(r <= diamMax/2);
% Create mask to convolve the image with.
maskMin = double(abs(x) <= diamMin/2);
maskMin = imrotate(maskMin, k); % Rotation of the mask.
lMaskMax = length(maskMax);
lMaskMin = length(maskMin);
if round(k/90) ~= k/90
maskMin = maskMin(round((lMaskMin-lMaskMax)/2+1.5):round(lMaskMin-...
(lMaskMin-lMaskMax)/2+0.5), round((lMaskMin-lMaskMax)/2+1.5):...
round(lMaskMin-(lMaskMin-lMaskMax)/2+0.5));
end % if
mask = double(maskMax & maskMin);
else % use rectangular mask
% code for creating rectangular mask
% ...
end % if end
end % end for
I would like to replace the elliptical mask if I choose (that is, I want to have both options available by setting a parameter rectMask), with an rectangular mask of with the same size and rotation. How can I do this based on current code?
My input data here are:
- diamMax
- diamMin
- k
- rectMask = 1 or 0
Accepted Answer
More Answers (1)
You could also just use poly2mask. This would avoid the overhead of imrotate.
M=256; N=256; %Image dimensions
diamMax=60; diamMin=40;
k=30;
imshow(getMask('rect',M,N,diamMin,diamMax,k))
imshow(getMask('ellipse',M,N,diamMin,diamMax,k))
function Mask=getMask(shape,M,N,diamMin,diamMax,k)
switch shape
case 'ellipse'
p=nsidedpoly(1000);
case 'rect'
p=nsidedpoly(4);
end
p=scale(p,[diamMax,diamMin]);
p=translate( rotate(p,-k) ,[M/2,N/2]);
V=p.Vertices;
Mask=poly2mask(V(:,1),V(:,2), M,N);
end
Categories
Find more on Image Arithmetic in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


