[2D] Largest Area

This function for Matlab gets all the largest areas from a binary image, larger than a given threshold as a factor [0-1] of the largest found area.

  1. function [outim] = largestarea(im,threshold)
  2. % Tim Zaman © 2010, TU Delft
  3. % 'largestarea' reads in a 2-d binary image and outputs a binary image,
  4. %   retaining only the largest blobs larger than the largest by a threshold.
  5. %
  6. % Usage: [outim] = largestarea(im,threshold)
  7. %
  8. % im - 2-d binary image
  9. % outim - Output binary image (with 1s and 0s)
  10. %
  11. % Example:
  12. %
  13. % im = imread('text.png');
  14. % outim = bwlargestblob(im,8);
  15.  
  16. connectivity=4;
  17.  
  18. if size(im,3)>1,
  19. error('largestarea accepts only 2 dimensional images');
  20. end
  21.  
  22. [imlabel totalLabels] = bwlabel(im,connectivity);
  23. sizeBlob = zeros(1,totalLabels);
  24. for i=1:totalLabels,
  25. sizeblob(i) = length(find(imlabel==i));
  26. end
  27.  
  28. max_global=max(sizeblob);
  29. i=0;
  30. while max(sizeblob)> max_global*threshold
  31. i=i+1;
  32. [maxno largestBlobNo(i)] = max(sizeblob);
  33. sizeblob(largestBlobNo(i))=1;
  34. end
  35.  
  36. outim = zeros(size(im),'uint8');
  37. for ii=1:i
  38. outim(find(imlabel==largestBlobNo(ii))) = 1;
  39. end
  40. outim=logical(outim);
  41. end

Tim Zaman

MSc Biorobotics. Specialization in computer vision and deep learning. Works at NVIDIA.

You may also like...