clc;
close all;
clearvars;
workspace;
format long g;
format compact;
fontSize = 16;
fprintf('Beginning to run %s.m ...\n', mfilename);
folder = [];
baseFileName = 'cereal1.png';
fullFileName = fullfile(folder, baseFileName);
if ~exist(fullFileName, 'file')
fullFileNameOnSearchPath = baseFileName;
if ~exist(fullFileNameOnSearchPath, 'file')
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
rgbImage = imread(fullFileName);
[rows, columns, numberOfColorChannels] = size(rgbImage)
grayImage = rgb2gray(rgbImage);
subplot(2, 2, 1);
imshow(rgbImage, []);
axis('on', 'image');
caption = sprintf('Image : "%s"', baseFileName);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
hp = impixelinfo();
hFig1 = gcf;
hFig1.Units = 'Normalized';
hFig1.WindowState = 'maximized';
hFig1.Name = 'Demo by Image Analyst';
fprintf('Masking image...\n');
[mask, maskedRGBImage] = createMask(rgbImage);
subplot(2, 2, 2);
imshow(mask, []);
hp = impixelinfo();
axis('on', 'image');
title('Initial Mask Image', 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
fprintf('Doing a morphological closing on the mask image...\n');
se = strel('disk', 2, 0);
mask = imclose(mask, se);
subplot(2, 2, 3);
imshow(mask, []);
hp = impixelinfo();
axis('on', 'image');
title('Final Mask Image', 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
fprintf('Making non red/orange grayscale in the RGB image...\n');
[redChannel, greenChannel, blueChannel] = imsplit(rgbImage);
mask = ~mask;
redChannel(mask) = grayImage(mask);
greenChannel(mask) = grayImage(mask);
blueChannel(mask) = grayImage(mask);
filteredRGBImage = cat(3, redChannel, greenChannel, blueChannel);
subplot(2, 2, 4);
imshow(filteredRGBImage, []);
hp = impixelinfo();
axis('on', 'image');
title('Non-red/orange set to gray scale.', 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
fprintf('Done running %s.m ...\n', mfilename);
msgbox('Done!');
function [BW,maskedRGBImage] = createMask(RGB)
I = rgb2hsv(RGB);
channel1Min = 0.908;
channel1Max = 0.113;
channel2Min = 0.143;
channel2Max = 1.000;
channel3Min = 0.425;
channel3Max = 1.000;
sliderBW = ( (I(:,:,1) >= channel1Min) | (I(:,:,1) <= channel1Max) ) & ...
(I(:,:,2) >= channel2Min ) & (I(:,:,2) <= channel2Max) & ...
(I(:,:,3) >= channel3Min ) & (I(:,:,3) <= channel3Max);
BW = sliderBW;
maskedRGBImage = RGB;
maskedRGBImage(repmat(~BW,[1 1 3])) = 0;
end