필터 지우기
필터 지우기

Image mask - apart from rectangle in the center

조회 수: 11 (최근 30일)
John Kau
John Kau 2015년 7월 27일
답변: John Kau 2015년 7월 29일
Hi!
I'm using this code (from the internet) to mask everything outside of the circle. I'm struggeling to adapt this code to replace the circle with a rectangle. Any suggestions?
maskGabor = (img);
[rNum, cNum, ~] = size(maskGabor);
% Define coordiantes and radius
[xx, yy] = ndgrid((1:rNum)-centerY, (1:cNum)-centerX); % generate grid with binary mask
mask = (xx.^2 + yy.^2)>radius^2; % define area outside of cirlce that will be masked
maskGabor(mask) = color; % color is gray
Many thanks, jk

채택된 답변

Cam Salzberger
Cam Salzberger 2015년 7월 29일
Hi John,
It is my understanding that you are able to create an image masked outside of a circular region, but would like to use a rectangular region instead. The key line to change in your code is the creation of the mask. Instead of finding all of the pixels outside of the circle, you are looking for all of the pixels that are to the left of the box, or the right of the box, or above, or below. This translates quite easily into a logical statement. See the code below for an example of a rectangularly-masked image:
% Acquire image
inputImage = imread('cameraman.tif');
% Determine image properties
[rNum, cNum, ~] = size(inputImage);
centerX = ceil(cNum/2);
centerY = ceil(rNum/2);
% Define parameters of the rectangle
windowWidth = 125;
windowHeight = 75;
% Create logical mask
[yy, xx] = ndgrid((1:rNum)-centerY, (1:cNum)-centerX);
mask = xx < -windowWidth/2 | xx > windowWidth/2 | ...
yy < -windowHeight/2 | yy > windowHeight/2;
% Mask image and show it
maskedImage = inputImage;
maskedImage(mask) = 128;
imshow(maskedImage)
I hope this helps.
-Cam

추가 답변 (1개)

John Kau
John Kau 2015년 7월 29일
Wow, thanks Cam, nice solution.
Mine is not that neat, since I wasn't able to manage the "OR" command for multiple factors properly... using 800 and 600 as fixed screen center.
top = (600 - (szY/2));
bottom = (600 + (szY/2));
left = (800 - (szX/2));
right = (800 + (szX/2));
rectMask = ones(cNum,rNum); % generate grid of ones
rectMask(top:bottom,left:right) = 0; % rectMask( Y values, X values)
rectMask = logical(rectMask);

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by