function res = DetectGrapes (I)

S = imread(I);
S1 = rgb2gray(S);

length = size(S1);
length = length(1);
width = size(S1);
width = width(2);

% Background for the PLOT
blackbg = zeros (length, width);
S2 = S1;

% Raw threshold
% for (i=1:length)
%     for (j=1:width)
%         S1 (i, j) = p * floor(S1(i,j)/p);
%     end
% end

%filtering lights on S2
for (i=1:length)
    for (j=1:width)
        if (S2(i,j) > 200)
            S2 (i,j) = 0;
        end
    end
end

S3 = S1;
S4 = S1;


%filtering lights on S1
S1 = adapthisteq (S1);

for (i=1:length)
    for (j=1:width)
        if (S1(i,j) > 200)
            S1 (i,j) = 0;
        end
    end
end

% but without losing accuracy
for i=1:768
    for j=1:1024
        if (or(S1(i,j) ==0, S2(i,j) ==0))
            S3(i,j) =0;
        end
    end
end

 %filtering reds
for (i=1:length)
    for (j=1:width)
        if (S(i,j, 1)/1.2 > S(i,j,2))       
            S3 (i,j) = 0;
        end
    end
end


S4 = medfilt2(S3,[4 4]);

for i=1:768
    for j=1:1024
        if S4(i,j) == 0
            S3(i,j) = 0;
        end
    end
end

S4 = medfilt2(S3,[10 10]);

for i=1:768
    for j=1:1024
        if S4(i,j) == 0
            S3(i,j) = 0;
        end
    end
end

S4 = medfilt2(S3,[10 10]);

for i=1:768
    for j=1:1024
        if S4(i,j) == 0
            S3(i,j) = 0;
        end
    end
end

% ADAPTIVE THRESHOLD
S5 = adaptivethreshold(S3, 4, 0);
S5 = imfill (S5, 'holes');
S5 = 1-S5;
S5 = medfilt2(S5,[10 10]);


% FINDING CIRCLES
[accum, circen, cirrad] = CircularHough_Grd(S5, [2 8], 10, 4);

if any(cirrad <= 0)
    inds = find(cirrad>0);
    cirrad = cirrad(inds);
    circen = circen(inds,:);
end

figure, imshow(blackbg);
hold on;
h = plot(circen(:,1), circen(:,2), 'r+');
for ii = 1 : size(circen, 1)
    rectangle('Position',[circen(ii,1) - cirrad(ii), circen(ii,2) - cirrad(ii), 2*cirrad(ii), 2*cirrad(ii)], 'Curvature', [1,1], 'edgecolor', 'w', 'linewidth', 1, 'FaceColor', 'w');
end
hold off;
a=getframe();
a = frame2im(a);
se = strel('disk',2);

a = imclose(a, se);

res = a;

end
