matlab中创建一个二值掩模,选择图像中心区域
时间: 2023-08-26 12:33:35 浏览: 116
在 Matlab 中创建二值掩模,可以使用以下步骤选择图像中心区域:
1. 读入图像,例如:
```matlab
img = imread('image.jpg');
```
2. 获取图像的大小,然后计算出图像中心的坐标,例如:
```matlab
[height, width, ~] = size(img);
center_x = round(width / 2);
center_y = round(height / 2);
```
3. 创建一个与图像大小相同的全黑掩模,例如:
```matlab
mask = zeros(height, width);
```
4. 根据需要选择中心区域的大小,例如选择一个宽度为 w,高度为 h 的矩形中心区域。
```matlab
w = 100;
h = 80;
```
5. 计算出矩形左上角和右下角的坐标,例如:
```matlab
x1 = center_x - w/2;
y1 = center_y - h/2;
x2 = center_x + w/2;
y2 = center_y + h/2;
```
6. 将矩形区域内的像素值设置为 1,例如:
```matlab
mask(y1:y2, x1:x2) = 1;
```
7. 可选步骤:在图像上显示掩模,例如:
```matlab
masked_img = img;
masked_img(repmat(~mask, [1, 1, 3])) = 0;
imshow(masked_img);
```
这将在图像上显示出选择的中心区域。
最终的代码如下所示:
```matlab
img = imread('image.jpg');
[height, width, ~] = size(img);
center_x = round(width / 2);
center_y = round(height / 2);
mask = zeros(height, width);
w = 100;
h = 80;
x1 = center_x - w/2;
y1 = center_y - h/2;
x2 = center_x + w/2;
y2 = center_y + h/2;
mask(y1:y2, x1:x2) = 1;
masked_img = img;
masked_img(repmat(~mask, [1, 1, 3])) = 0;
imshow(masked_img);
```
运行该代码,即可得到选择的中心区域的二值掩模。
阅读全文
相关推荐
















