%%To clear the matlab window and close figure window
workspace;
%%
%%Get an image and convert into rgb& hsv
%vid = videoinput('winvideo', 1, 'YUY2_640x480');
colorimage=getsnapshot(vid);
%src = getselectedsource(vid);
%vid.FramesPerTrigger = 1;
% colorimage=imread('1.jpg');
% colorimage=start(vid);
dblimage=im2double(colorimage);
redimage=colorimage(:,:,1);
blueimage=colorimage(:,:,2);
greenimage=colorimage(:,:,3);
hsvImage = rgb2hsv(colorimage);
hImage = hsvImage(:,:,1);
sImage = hsvImage(:,:,2);
vImage = hsvImage(:,:,3);
%%
%Thresholding the image and creating mask
hueThresholdLow = 0;
hueThresholdHigh = graythresh(hImage);
saturationThresholdLow = graythresh(sImage);
saturationThresholdHigh = 1.0;
valueThresholdLow = graythresh(vImage);
valueThresholdHigh = 1.0;
hueMask = (hImage >= hueThresholdLow) & (hImage <= hueThresholdHigh);
saturationMask = (sImage >= saturationThresholdLow) & (sImage <= saturationThresholdHigh);
valueMask = (vImage >= valueThresholdLow) & (vImage <= valueThresholdHigh);
%%
%creating yellow mask
yellowObjectsMask = uint8(hueMask & valueMask);
%figure,imshow(yellowObjectsMask, []);
yellowObjectsMask = uint8(bwareaopen(yellowObjectsMask, 100));
%figure,imshow(yellowObjectsMask, []);
%%masking noise
mask = strel('disk',8);
%figure,imshow(yellowObjectsMask, []);
% title('Masked Image')
yellowObjectsMask1 = imerode(yellowObjectsMask,mask);
% yellowObjectsMask1 = imerode(yellowObjectsMask1,mask);
% yellowObjectsMask1 = imerode(yellowObjectsMask1,mask);
% yellowObjectsMask1 = imerode(yellowObjectsMask1,mask);
figure,imshow(yellowObjectsMask1, []);
title('Disk Masked Image')
% structuringElement = strel('disk', 2);
% yellowObjectsMask = imclose(yellowObjectsMask, structuringElement);
% % Fill in any holes in the regions, since they are most likely red also.
% yellowObjectsMask = uint8(imfill(yellowObjectsMask, 'holes'));
% %figure,imshow(yellowObjectsMask, []);
%
% % We need to convert the type of yellowObjectsMask to the same data type as hImage.
% yellowObjectsMask = cast(yellowObjectsMask, class(colorimage));
% maskedImageR = yellowObjectsMask .* colorimage(:,:,1);
% maskedImageG = yellowObjectsMask .* colorimage(:,:,2);
% maskedImageB = yellowObjectsMask .* colorimage(:,:,3);
% maskedRGBImage = cat(3, maskedImageR, maskedImageG, maskedImageB);
% %figure,imshow(maskedRGBImage);
%figure,imshow(colorimage);