我编写了一些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像素的像素,变为“ off / 0 / black”像素,然后将其从输出中删除。
有人知道我会怎么做吗?
我的代码如下所示。
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
答案 0 :(得分:0)
只需在末尾添加一个循环,即可检查每个索引有多少像素。
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