MATLAB二值化图像指定区域变黑
时间: 2023-07-04 21:06:51 浏览: 58
可以使用 MATLAB 中的逻辑索引和赋值操作来实现指定区域变黑。具体步骤如下:
1. 首先将原始图像进行二值化处理,将感兴趣的区域转为逻辑索引。例如,假设需要将图像中心的一个正方形区域变为黑色,可以使用以下代码:
```matlab
img = imread('image.jpg'); % 读取原始图像
bw = imbinarize(img); % 二值化处理
[y, x] = size(img);
center_size = min(x, y) / 2; % 计算正方形区域的边长
center_x = floor(x / 2); % 计算正方形区域的中心点坐标
center_y = floor(y / 2);
center_idx = (abs(1:x - center_x) <= center_size & ...
abs(1:y - center_y)' <= center_size); % 正方形区域的逻辑索引
```
2. 将指定区域的像素值赋为黑色。可以使用逻辑索引和赋值操作来实现:
```matlab
img(center_idx) = 0; % 将指定区域的像素值赋为黑色(0)
```
3. 可以将结果图像显示出来,检查是否满足要求:
```matlab
imshow(img);
```
完整代码如下:
```matlab
img = imread('image.jpg'); % 读取原始图像
bw = imbinarize(img); % 二值化处理
[y, x] = size(img);
center_size = min(x, y) / 2; % 计算正方形区域的边长
center_x = floor(x / 2); % 计算正方形区域的中心点坐标
center_y = floor(y / 2);
center_idx = (abs(1:x - center_x) <= center_size & ...
abs(1:y - center_y)' <= center_size); % 正方形区域的逻辑索引
img(center_idx) = 0; % 将指定区域的像素值赋为黑色(0)
imshow(img); % 显示结果图像
```
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)