function [roiPix myStd] = getPixStd(rgbImg, filtSize)
% read and check image, get size

[nRows nCols nLyrs] = size(rgbImg);
if (nLyrs ~= 3)
error('Image is not RGB!');
end
nPix = nRows * nCols;
% display original image
figure;
imshow(rgbImg);
title('RGB image');

% smooth image
fprintf('Smoothing image ...\n');
myFilt = ones(filtSize) ./ filtSize^2;
smoothImg = imfilter(rgbImg, myFilt);

% print some instructions with the function fprintf()
fprintf('Use mouse to delineate region for color sample\n');
fprintf('Click to place a vertex\n');
fprintf('Right-click and select Create Mask to close polygon\n');

% open a new figure for the region selection and call roipoly()
figure;
title('Select region');
roiMask = roipoly(rgbImg);
roiMask2 = roipoly(rgbImg);
roiMask3 = roipoly(rgbImg);

roiMask = roiMask | roiMask2 | roiMask3;

% use the mask to extract the color region
fprintf('Masking region ...\n');
red = immultiply(roiMask, smoothImg(:,:,1));
green = immultiply(roiMask, smoothImg(:,:,2));
blue = immultiply(roiMask, smoothImg(:,:,3));
roiImg = cat(3, red, green, blue);

% display the color region
figure;
imshow(roiImg);
title('Color sample');

% reshape image into vector of size nPix by 3
imgPix = double(reshape(smoothImg, nPix, 3));
% reshape roi region into vector of size nPix by 3
roiPix = double(reshape(roiImg, nPix, 3));
% find the nonzero entries in the mask
roiIdx = find(roiMask);
% keep only the RGB pixels corresponding to the mask
roiPix = roiPix(roiIdx, 1:3);

% get statistics
fprintf('Computing region statistics ...\n');
% standard deviation (use the max value for R, G, or B)
myStd = max(std(roiPix))
