Question

I used connected component labeling algorithm (bwconncomp) to label the different parts of a binary image (MATLAB). Now i need to calculate the area of different labels and remove the labels with smaller area. Can i use the default area finding command or is there any specific commands for that in matlab...Help..

Was it helpful?

Solution

From the documentation:

CC = bwconncomp(BW) returns the connected components CC found in BW. The binary image BW can have any dimension. CC is a structure with four fields...

The final field in CC is PixelIdxList, which is:

[a] 1-by-NumObjects cell array where the kth element in the cell array is a vector containing the linear indices of the pixels in the kth object.

You can find the area of each label by looking at the length of the corresponding entry in the cell array. Something like:

areas_in_pixels = cellfun(@length, CC.PixelIdxList);

The PixelIdxList is a cell array, each member of which contains the linear indexes of the pixels present in that connected component. The line of code above finds the length of each cell in the cell array - i.e. the number of pixels in each connected component.

I've used cellfun to keep the code short and efficient. A different way of writing the same thing would be something like:

areas_in_pixels = nan(1, length(CC.PixelIdxList);
for i = 1:length(CC.PixelIdxList)
  areas_in_pixels(i) = length(CC.PixelIdxList{i});
end 

For each connected component, you can then find the size of that component in pixels by accessing an element in areas_in_pixels:

areas_in_pixels(34)   %# area of connected component number 34

OTHER TIPS

If you don't want to write lots of code like above just use built-in functions of MATLAB to detect the area. Label your components and from the properties of the component you can find out the area of that component. Suppose Bw is the binary image:

[B,L] = bwboundaries(Bw,'noholes');
stats = regionprops(L,'Area','perimeter');

for k = 1:length(B) 
  area(k)=stats.Area;
end

You can make this better still by avoiding the for loop with the following:

[B,L] = bwboundaries(Bw,'noholes');
stats = regionprops(L,'Area','perimeter');
area = [stats.Area];

Best, -Will

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top