在matlab中定义掩码的代码

code to define mask in matlab

我正在开发一个 CBIR 系统,我必须按以下方式分割我的 RGB 图像:

我正在 matlab 中实现代码,但无法为其构建合适的掩码。 我使用了 imellipse,但这需要使用 imshow 实现的图像句柄,但我不想显示我的图像。 我的代码是

img=imread('peppers.png');
h_im=imshow(img); %I want to get rid of imshow because I don't want to show the image

[height, width, planes]=size(img);
%(cX,cY) is image center
cX=width/2;
cY=(height)/2;

%Here I define my ROI which is an ellipse that stretches to 75 percent of
%height and width of the image
e=imellipse(gca,[(1/2-3/8)*width, (1/2-3/8)*height,(3/4)*width,(3/4)*height]);
mymask=createMask(e,h_im);

%extending mask to three channels
mymask=repmat(mymask,[1 1 3]);
ROI=img;
ROI(mymask==0)=0;
figure, imshow(ROI);

有点乱,但您可以创建一个 'hidden' 图形。唯一的区别是我在代码的开头添加了:figure('Visible', 'off')

figure('Visible', 'off');

img=imread('peppers.png');
h_im = imshow(img); %I want to get rid of imshow because I don't want to show the image

[height, width, planes]=size(img);
%(cX,cY) is image center
cX=width/2;
cY=(height)/2;

%Here I define my ROI which is an ellipse that stretches to 75 percent of
%height and width of the image
e=imellipse(gca,[(1/2-3/8)*width, (1/2-3/8)*height,(3/4)*width,(3/4)*height]);
mymask=createMask(e,h_im);

%extending mask to three channels
mymask=repmat(mymask,[1 1 3]);
ROI=img;
ROI(mymask==0)=0;
figure, imshow(ROI);

您可以自己生成椭圆蒙版,而不是使用 imellipse 命令。

% Create a meshgrid the same size of the image in order to generate the mask
[x y] = meshgrid(1:size(img, 1), 1:size(img, 2));

% Create the eclipse mask using the general form of an eclipse
% This will be centered in the middle of the image 
% and have a height and width of 75% of th eimage
A = (0.75/2)*size(img, 2);
B = (0.75/2)*size(img, 1);
mask = A^2*(x - floor(size(img, 1)/2)).^2 + B^2*(y - floor(size(img, 2)/2)).^2<=A^2*B^2;

% Apply the eclipse mask
masked_image = img.*repmat(mask, [1, 1, 3]);

我认为此代码易于理解且易于调整以解决图像的任意部分(它与您的代码具有相同的输出):

img = imread('peppers.png');

% define the size of your ellipse relatively to the image dimension
factor = 0.75;

hwidth = size(img, 2) / 2.0;
hheight = size(img, 1) / 2.0;

a = hwidth * factor;
b = hheight * factor;

[x, y] = meshgrid(1:hwidth, 1:hheight);

% simple ellipse equation gets us part three of your mask
bottom_right_mask = (((x.^2)/a^2+(y.^2)/b^2)<=1); 

% flip to get the remaining ones
top_right_mask = flipud(bottom_right_mask);
bottom_left_mask = fliplr(bottom_right_mask);
top_left_mask = flipud(bottom_left_mask);

mask = [top_left_mask, top_right_mask; ...
        bottom_left_mask, bottom_right_mask];

multichannel_mask = repmat(mask,[1 1 3]);

ROI = img;
ROI(multichannel_mask==0) = 0;

figure;
imshow(ROI);