【发布时间】:2019-09-24 02:48:40
【问题描述】:
我在 MATLAB 中编写了一些代码,它使用设定的阈值将图像(星形)转换为二进制图像,然后标记高于此阈值的每个像素簇(星形)。标签产生输出: 例如
[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]
所以每个由 1、2、3 等组成的星团代表一颗星。我使用此链接提供的答案:How to find all connected components in a binary image in Matlab? 来标记像素。 我也不能使用图像处理工具箱。 我到目前为止的代码如下所示。
我现在如何找到图像中每个像素簇的质心?
clc
clear all
close all
img=imread('star.jpg');
binary_image=convert2binary(img);
imshow(binary_image);
visited = false(size(binary_image));
[rows, cols] = size(binary_image);
B = zeros(rows, cols);
ID_counter = 1;
for row = 1:rows
for col = 1:cols
if binary_image(row, col) == 0
visited(row, col) = true;
elseif visited(row, col)
continue;
else
stack = [row col];
while ~isempty(stack)
loc = stack(1,:);
stack(1,:) = [];
if visited(loc(1),loc(2))
continue;
end
visited(loc(1),loc(2)) = true;
B(loc(1),loc(2)) = ID_counter;
[locs_y, locs_x] = meshgrid(loc(2)-1:loc(2)+1, loc(1)-1:loc(1)+1);
locs_y = locs_y(:);
locs_x = locs_x(:);
out_of_bounds = locs_x < 1 | locs_x > rows | locs_y < 1 | locs_y > cols;
locs_y(out_of_bounds) = [];
locs_x(out_of_bounds) = [];
is_visited = visited(sub2ind([rows cols], locs_x, locs_y));
locs_y(is_visited) = [];
locs_x(is_visited) = [];
is_1 = binary_image(sub2ind([rows cols], locs_x, locs_y));
locs_y(~is_1) = [];
locs_x(~is_1) = [];
stack = [stack; [locs_x locs_y]];
end
ID_counter = ID_counter + 1;
end
end
end
function [binary] = convert2binary(img)
[x, y, z]=size(img);
if z==3
img=rgb2gray(img);
end
img=double(img);
sum=0;
for i=1:x
for j=1:y
sum=sum+img(i, j);
end
end
threshold=100 % or sum/(x*y);
binary=zeros(x,y);
for i=1:x
for j=1:y
if img(i, j) >= threshold
binary(i, j) = 1;
else
binary(i, j)=0;
end
end
end
end
【问题讨论】:
标签: matlab image-processing centroid