I want to extract only the grapes from the images. Unfortunately, sometimes I don't get the grapes exactly.

I have a code that doesn't work well in all cases. Sometimes, it does not differentiate between the shadows and the grapes.

The example input image:

The result I'm getting:

And this is my code:

RGB = imread('DSC02807.JPG');
GRAY = rgb2gray(RGB);

threshold = graythresh(GRAY);
originalImage = im2bw(GRAY, threshold);

originalImage = bwareaopen(originalImage,250);

SE = strel('disk',10);
IM2 = imclose(originalImage,SE);

originalImage = IM2;

imshow(originalImage);

• I Think this question is more appropriate at SE dsp... – bla Oct 23 '12 at 23:59
• @nate, thank you.. but what does SE dsp mean? I read that it is small environment, but I don't really know :/ can you tell me please about that? – Alon Shmiel Oct 24 '12 at 0:07
• Alon, I've tested your code, and I really don't understand what's not accurate about it. it filters out the shadows very well. – bla Oct 24 '12 at 6:31
• @Alon Shmiel The input/output pair you provided seems to produce good results. Maybe you could point to specifically where the problem in this particular output is, or, alternatively, post an input/output image pair where the problems are more easily visible? – penelope Oct 24 '12 at 13:09
• I think what the original problem of Alon's is that of removing the dark shadows directly beneath each grape and not the ones which look like an elongated cylinder. You need to precisely segment the grape alone - the shapes look weird and not oval or circular coz of the shadows. Or are they not shadows but the thinnest outer skin of the grape refracting light to look like that? – user3178 Oct 25 '12 at 18:05

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<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))

• I agree, the shadows look fine. Instead it's the highlights on the grapes (see grapes 4 and 5 on the top line for instance) that cause some irregularities. – Junuxx Oct 24 '12 at 7:38
• This answer gives the best explanation. @Alon Shmiel: Please be more specific about the problem regarding the shadows and post an example where it doesn't fit. Kind regards – mchlfchr Oct 26 '12 at 7:50