clc;
clearvars;
close all;

%Load image
img = imread('dog_lift_smol.png'); 

figure;
imshow(img);

% Convert to HSV color space
hsvImg = rgb2hsv(img);

% Extract HSV channels
H = hsvImg(:,:,1); % Hue
S = hsvImg(:,:,2); % Saturation
V = hsvImg(:,:,3); % Value


%% Define threshold for brown

brown_H_low = 20/255;
brown_H_high = 55/255;

brown_S_low = 40/255;   
brown_S_high = 110/255;  

brown_V_low = 180/255; 
brown_V_high = 255/255;

%% Color mask

color_mask = (H >= brown_H_low) & (H <= brown_H_high);

figure;
imshow(H);

figure;
imshow(color_mask);

%% Saturation mask

satur_mask = (S >= brown_S_low) & (S <= brown_S_high);

figure;
imshow(S);

figure;
imshow(satur_mask);

%% Value mask

value_mask = (V >= brown_V_low) & (V <= brown_V_high);

figure;
imshow(V);

figure;
imshow(value_mask);

%% Combined mask

mask = color_mask & satur_mask & value_mask;

figure;
imshow(mask);


%% Mask cleaning

mask = bwareaopen(mask, 15);

figure;
imshow(mask);


%Erode
%Have to create "structural element"
se = strel('disk', 20, 0);

mask_dilate = imdilate(mask, se);
mask_erode = imerode(mask_dilate, se);

figure;
imshow(mask_erode);


%% Mask the image

img_copy = img;
img_copy(repmat(~mask_erode, [1 1 3])) = 0;

figure
imshow(img_copy);