Search code examples
imagematlabimage-processingcomputer-visionconnected-components

Group numbers in a certain way in MATLAB


I finding the connected components in an image without using the computer vision toolbox in Matlab.

In the first scan of the given image, I have given labels to each pixel. I also have created a table that gives me the list of the components that are connected to each other. The table looks like this:

1   5
1   5
2   4
3   5
8   5
2   6

This table implies that all the pixels with labels 1 and 5 are connected,2 and 4 are connected, 3 and 5 are connected and so on. Also, since 1 and 5 are connected and 3 and 5 are also connected, this implies 1 and 3 are also connected.

I want to find a way to group all these components together. Is there any possible way?? Or some way that every connected pixel gets a label equivalent to the label with the minimum value i.e. if 4, 7 and 12 pixels are connected, all the pixels with labels 4, 7 and 12 should get a label of value 4.


Solution

  • It appears that you want to compute the connected components of your graph. This can be done fairly easily in MATLAB without any additional toolboxes.

    e = [1   5; ...
         1   5; ...
         2   4; ...
         3   5; ...
         8   5; ...
         2   6];
    % MATLAB doesn't support repeated edges so remove them
    e = unique(sort(e,2),'rows');
    % create a graph
    G = graph(e(:,1),e(:,2));
    % plot the graph (optional)
    plot(G);
    % find connected components
    bins = conncomp(G);
    % get the indicies of nodes in each cluster
    cluster = arrayfun(@(v)find(bins==v),1:max(bins),'UniformOutput',false);
    

    Results

    enter image description here

    >> cluster{1}
    ans = 1     3     5     8
    >> cluster{2}
    ans = 2     4     6
    >> cluster{3}
    ans = 7