用matlab2014a编写代码1、写代码在“coins.png”硬币图像中,(1)、任选一个硬币中的点作为种子点,实现基于该点的区域生长,如图Fig.6.1.1和Fig.6.1.2;(2)、扩展实现:对整幅图像中每个硬币进行“自动”生长(自动选择种子点),实现所有硬币的自动生长,并填充;
时间: 2024-02-29 07:52:23 浏览: 109
基于区域生长实现图像分割附matlab代码
5星 · 资源好评率100%
好的,以下是Matlab代码实现:
1、实现基于种子点的区域生长
```matlab
% 读取图像
I = imread('coins.png');
% 显示图像
imshow(I);
% 选取种子点
[x, y] = ginput(1);
% 转换为整数
x = round(x);
y = round(y);
% 获取种子点的像素值
seed_value = I(y, x);
% 初始化标记矩阵
label = zeros(size(I));
label(y, x) = 1;
% 初始化生长队列
queue = [x, y];
% 定义邻域
neighborhood = [0, 1; 1, 0; 0, -1; -1, 0];
% 区域生长
while ~isempty(queue)
% 弹出队列首个像素坐标
current_pixel = queue(1, :);
queue(1, :) = [];
% 遍历邻域
for i = 1:size(neighborhood, 1)
% 计算邻域像素坐标
neighbor_pixel = current_pixel + neighborhood(i, :);
% 判断是否越界
if neighbor_pixel(1) < 1 || neighbor_pixel(1) > size(I, 2) || neighbor_pixel(2) < 1 || neighbor_pixel(2) > size(I, 1)
continue;
end
% 判断是否已标记
if label(neighbor_pixel(2), neighbor_pixel(1)) == 1
continue;
end
% 获取邻域像素值
neighbor_value = I(neighbor_pixel(2), neighbor_pixel(1));
% 判断是否满足条件
if abs(neighbor_value - seed_value) <= 15
% 标记当前像素
label(neighbor_pixel(2), neighbor_pixel(1)) = 1;
% 添加到生长队列
queue = [queue; neighbor_pixel];
end
end
end
% 绘制区域
hold on;
[h, w] = find(label);
plot(w, h, 'r.');
```
2、实现自动生长并填充每个硬币
```matlab
% 读取图像
I = imread('coins.png');
% 显示图像
imshow(I);
% 初始化标记矩阵
label = zeros(size(I));
% 初始化硬币区域数量
coins_num = 0;
% 定义阈值
threshold = 15;
% 区域生长
for i = 1:size(I, 1)
for j = 1:size(I, 2)
% 判断是否已标记
if label(i, j) == 0
% 获取当前像素值
seed_value = I(i, j);
% 初始化标记矩阵和生长队列
current_label = zeros(size(I));
current_label(i, j) = 1;
queue = [j, i];
% 定义邻域
neighborhood = [0, 1; 1, 0; 0, -1; -1, 0];
% 区域生长
while ~isempty(queue)
% 弹出队列首个像素坐标
current_pixel = queue(1, :);
queue(1, :) = [];
% 遍历邻域
for k = 1:size(neighborhood, 1)
% 计算邻域像素坐标
neighbor_pixel = current_pixel + neighborhood(k, :);
% 判断是否越界
if neighbor_pixel(1) < 1 || neighbor_pixel(1) > size(I, 2) || neighbor_pixel(2) < 1 || neighbor_pixel(2) > size(I, 1)
continue;
end
% 判断是否已标记
if current_label(neighbor_pixel(2), neighbor_pixel(1)) == 1
continue;
end
% 获取邻域像素值
neighbor_value = I(neighbor_pixel(2), neighbor_pixel(1));
% 判断是否满足条件
if abs(neighbor_value - seed_value) <= threshold
% 标记当前像素
current_label(neighbor_pixel(2), neighbor_pixel(1)) = 1;
% 添加到生长队列
queue = [queue; neighbor_pixel];
end
end
end
% 计算当前硬币的面积
area = sum(sum(current_label));
% 判断是否为硬币
if area > 1000 && area < 5000
% 更新标记矩阵
label(current_label == 1) = coins_num + 1;
% 绘制硬币区域
hold on;
[h, w] = find(current_label);
plot(w, h, 'r.');
% 填充硬币区域
I(current_label == 1) = median(median(I));
% 硬币数量加1
coins_num = coins_num + 1;
end
end
end
end
```
注意:第2个问题的代码运行时间较长,大约需要几分钟的时间,请您耐心等待。
阅读全文