matlab - 如何将某个簇大小以上的“开”像素簇更改为“关”像素
问题描述
我制作了一些 MATLAB 代码,通过使用设定的阈值将图像(星形)转换为二进制图像。然后它找到并标记相互连接的“on/1/white”像素簇,然后给出如下输出:
[1 1 1 0 0 0 0 0 0
1 1 0 0 0 2 2 2 0
0 0 0 3 3 0 2 0 0
0 0 0 3 3 0 0 0 0]
为了创建集群,代码使用一个计数器来为每个集群提供它自己的唯一 ID,例如 1、2 或 3 等。但是我现在希望能够转动超过一定大小的像素集群,例如大于 12像素大小,转换为“关闭/0/黑色”像素,并将它们从输出中删除。
有谁知道我会怎么做?
我的代码如下所示。
visited = false(size(binary_image)); % initialise an array with same size as image array that is logical. This records which pixels have been visited.
[rows, cols] = size(binary_image);
B = zeros(rows, cols); % initialise an output array with all 0's that is the same size as the image array. Any 0's left don't belong to connected pixels.
ID_counter = 1; % Labels connected pixels with unique ID's and keeps track of given ID's
for row = 1:rows % search through rows of binary_image
for col = 1:cols % search through columns of binary_image
if binary_image(row, col) == 0
visited(row, col) = true; % if position == 0 mark as visited and continue
elseif visited(row, col)
continue; % if already visited position then continue
else
stack = [row col]; % if not visited before create stack with this location
while ~isempty(stack) % while stack isn't empty
loc = stack(1,:);
stack(1,:) = []; % remove this location from stack
if visited(loc(1),loc(2))
continue; % if stack location already visited then continue
end
visited(loc(1),loc(2)) = true; % is not visited before then mark as visited
B(loc(1),loc(2)) = ID_counter; % mark this location in output array using unique ID
[locs_y, locs_x] = meshgrid(loc(2)-1:loc(2)+1, loc(1)-1:loc(1)+1); % given this location, check 8 neighbouring pixels (N,E,S,W,NE,NW,SE,SW)
locs_y = locs_y(:);
locs_x = locs_x(:);
out_of_bounds = locs_x < 1 | locs_x > rows | locs_y < 1 | locs_y > cols; % get rid of locations that are out of bounds of image
locs_y(out_of_bounds) = [];
locs_x(out_of_bounds) = [];
is_visited = visited(sub2ind([rows cols], locs_x, locs_y)); % get rid of locations already visited
locs_y(is_visited) = [];
locs_x(is_visited) = [];
is_1 = binary_image(sub2ind([rows cols], locs_x, locs_y)); % get rid of locations that are 0
locs_y(~is_1) = [];
locs_x(~is_1) = [];
stack = [stack; [locs_x locs_y]]; % add remaining locations to stack
end
ID_counter = ID_counter + 1; % increase the unique ID by 1 after every cluster labelling
end
end
end
解决方案
只需在末尾添加一个循环,您可以在其中检查每个索引有多少像素。
pixel_limt = 12;
for jj = 1:length(ID_counter)
id_index = find(B == jj);
if numel(id_index) > pixel_limit
B(id_index) = 0;
end
end
推荐阅读
- javascript - 如何从反应挂钩返回父组件的回调?比如返回上传的url列表
- python - 初学者问题,编写我的第一个代码。不确定这个问题
- tensorflow - 从 1.x 到 2.x 的 TensorFlow 端口模型
- ruby - 在字符串中插入一个空格
- azure - 是否可以在 Azure Web App Service 中访问 Azure 虚拟机本地站点?
- c++ - 我不明白这些错误是什么意思
- python - 为什么 numpy.random.normal(0,1,N) 的结果加起来不等于 0?
- regex - 使用正则表达式解析凌乱的货币字符串PostgreSQL
- swift - 在保存之前/之后旋转下载的(image.png)?
- asp.net-core-mvc - 使用 MVC 核心操作方法,我想将 JsonResult 传递给视图。从模型中检索数据。做同样的事情的最好方法是什么?