title: Create mask from bwtraceboundary in Matlab
body: <p>I'm trying to create a mask (or similar result) in order to erase pieces of a binary image that are not attached to the object surrounded by the boundary. I saw this thread (<a href="http://www.mathworks.com/matlabcentral/answers/120579-converting-boundary-to-mask" rel="nofollow noreferrer">http://www.mathworks.com/matlabcentral/answers/120579-converting-boundary-to-mask</a>) to do this from bwboundaries, but I'm having trouble making suitable changes to it. My goal is to use this code to isolate the part of this topography map that is connected, and get rid of the extra pieces. I need to retain the structure inside of the bounded area, as I was then going to use bwboundaries to create additional boundary lines of the main object's "interior" structure. </p>
  
  <p><img src="https://i.stack.imgur.com/jhLOw.png" alt="enter image description here"></p>
  
  <p>The following is my code to first create the single boundary line by searching for the bottom left pixel of the black area to begin the trace. It just looks for the first column of the image that isn't completely white and selects the last black pixel. The second section was then to create the inner boundary lines. Note that I am attempting this two step process, but if there is a way to do it with only one I'd like to hear that solution as well. Ultimately I just want boundaries for the main, large black area and the holes inside of it, while getting rid of the extra pieces hanging around.</p>
  
  <pre><code> figName='Images/BookTrace_1';
  
  BW = imread([figName,'.png']);
      BW=im2bw(BW);
      imshow(BW,[]);
  
      for j=1:size(BW,2)
          if sum(BW(:,j))~=sum(BW(:,1))
              corner=BW(:,j);
              c=j-1;
              break
          end
      end
      r=find(corner==0);
      r=r(end);
  
      outline = bwtraceboundary(BW,[r c],'W',8,Inf,'counterclockwise');
      hold on;
      plot(outline(:,2),outline(:,1),'g','LineWidth',2);
  
  
  [B,L] = bwboundaries(BW);
  hold on
  for k = 1:length(B)
      boundary = B{k};
      plot(boundary(:,2), boundary(:,1), 'g', 'LineWidth', 2)
  end
  </code></pre>
  
  <p>Any suggestions or tips are greatly appreciated. If there are questions, please let me know and I'll update the post. Thank you!</p>
  
  <p>EDIT: For clarification, my end goal is as in the below image. I need to trace all of the outer and inner boundaries attached to the main object, while eliminating any spare small pieces that are not attached to it.
  <img src="https://i.stack.imgur.com/Ha4nq.png" alt="enter image description here"></p>