Remove Shadows from Contour of an Object (Grapes)
This is what your code produces (using colormap(hot) with white boundaries that are obtained from IM2):


I think the shadows are nicely treated, why are you thinking that your code doesn't notice between shadow to grapes?

This is the code used for producing this image

bw=IM2&lt;1;
[B,L] = bwboundaries(bw,'noholes'); % fill any holes, so that regionprops can be used to estimate
imagesc(GRAY); hold on
for k = 1:length(B) 
    boundary = B{k};
    plot(boundary(:,2), boundary(:,1), 'w', 'LineWidth', 1); hold on
end
colormap(hot(256))