matlab m掩膜
时间: 2023-11-06 07:01:24 浏览: 96
matlab中的m掩膜是指通过给定的图片生成一个半径为m/2的圆形掩膜,圆形内的像素值被设置为1,圆形外的像素值被设置为0。具体实现方法是使用meshgrid函数生成矩阵对应的每一个坐标,然后计算出每一个点到圆心的距离的平方,根据距离是否小于等于r*r来判断点是否在圆内或圆外,最后根据判断结果给像素赋值。以下是该掩膜的示例代码:
```matlab
function [masked_im,circ_mask] = circle_mask(im)
circ_mask = im;
im_size = size(im);
m = im_size(1); % 图像矩阵的行数
n = im_size(2); % 图像矩阵的列数
r = floor(m/2); % 生成圆的半径
m1 = -m/2:m/2-1; % 把圆心变到矩阵的中间
n1 = -n/2:n/2-1;
[x,y] = meshgrid(m1,n1);
circle = x.^2 + y.^2; % 计算出每一点到圆心的距离的平方
circ_mask(find(circle > r*r)) = 0; % 找到圆外的元素,赋值为0
masked_im = circ_mask; % 这就是被遮掩后的图像
circ_mask(find(circle <= r*r)) = 1; % 找到圆内的元素,并赋值为1,这是图像掩膜
end
inputfilename = "E:\shipwreck.jpg";
im = imread(inputfilename);
im = rgb2gray(im); % 转化为灰度图
figure(10)
subplot(1,2,1)
imshow(im)
[im,im_mask] = circle_mask(im);
subplot(1,2,2)
imshow(im)
```
阅读全文
相关推荐
















