Detecting and isolating part of an image I'm working with cross-sectional CT scans of the leg using matlab's image processing toolbox.  Part of what I'm attempting to do is to automatically isolate the leg in any image, which requires removing any extraneous objects that are present in the image.  So far my code is able to take out most objects, which works for the majority of my images.  However, some of the images have an object that is flush with the leg, which my code isn't able to remove.

Here's an example of the problem: The first image shows the original image, and the second one shows the "filtered" image, after it has gotten rid of extraneous objects.  But as you can see, there is still something outside of the leg cross-section that I would like to get rid of.





I've thought of using something to detect ellipses, but unfortunately some of my images are not very good homogenous shapes (like the one below).



And here's the current code I have:

% Read input file
inputfile = dlmread(filename,';');

% Normalise input file (0 to 1) &amp; show original image
I_original = mat2gray(inputfile,[min(inputfile(:)) max(inputfile(:))]);
figure; imshow(I_original)

% Detect leg
BW1 = im2bw(I_original,.2);
BW2 = imfill(BW1,'holes');

% Remove misc. objects around leg (i.e., stray objects &lt;5000 pixels)
BW_final = bwareaopen(BW2,5000);

% Generate filtered image
I_filtered = I_original;
I_filtered(imcomplement(BW_final)) = NaN;
figure; imshow(I_filtered)


Any suggestions on how to fix this would be appreciated!  Thanks!
Since the Extraneous part is connected with leg section via a small thread like thing, Try converting it to binary Image, and then eroding the image to get rid of smaller objects. That should disconnect your both objects. Then choose the object with biggest area.

Helpful functions - im2bw, imerode, rogionprops.