Reputation:
I've made some MATLAB code that turns an image (stars) into a binary image by using a set threshold. It then finds and labels the clusters of 'on/1/white' pixels that are connected to each other and then gives an output like:
[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]
To create the clusters the code uses a counter to give each cluster it's own unique ID, such as 1, 2 or 3 etc. However I now want to be able to turn the pixel clusters that are above a certain size, e.g. larger than 12 pixels in size, into 'off/0/black' pixels and remove them from the output.
Does anyone know how I would do this?
My code is shown below.
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
Upvotes: 1
Views: 88
Reputation: 314
Just add a loop at the end where you examine how many pixels there are with each index.
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
Upvotes: 0