clc;
close all;
workspace;
format long g;
format compact;
fontSize = 16;
baseFileName = 'A2.jpg';
folder = pwd;
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)
subplot(2, 3, 1);
imshow(rgbImage, []);
impixelinfo;
axis on;
caption = sprintf('Original Color Image\n%s', baseFileName);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo();
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0.05 1 0.95]);
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
drawnow;
redChannel = rgbImage(:, :, 1);
greenChannel = rgbImage(:, :, 2);
blueChannel = rgbImage(:, :, 3);
mask = redChannel > greenChannel;
subplot(2, 3, 2);
imshow(mask);
caption = sprintf('Color Segmentation Mask Image');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
impixelinfo;
axis('on', 'image');
drawnow;
mask = imfill(mask, 'holes');
mask = bwareafilt(mask, 1);
mask = imerode(mask, true(5));
subplot(2, 3, 3);
imshow(mask);
title('Final Mask', 'FontSize', fontSize, 'Interpreter', 'None');
impixelinfo;
axis('on', 'image');
maskedRgbImage = bsxfun(@times, rgbImage, cast(mask, 'like', rgbImage));
subplot(2, 3, 4);
imshow(maskedRgbImage);
title('Masked RGB Image', 'FontSize', fontSize, 'Interpreter', 'None');
impixelinfo;
axis('on', 'image');
set(gca,'ydir','reverse')
conversion = 0.9183;
addMM = @(x) sprintf('%.3fmm', x * conversion);
xticklabels(cellfun(addMM, num2cell(xticks'), 'UniformOutput', false));
yticklabels(cellfun(addMM, num2cell(yticks'), 'UniformOutput', false));
topRow = 1;
grayLevelSum = zeros(1, columns);
heights = zeros(1, columns);
[rows, columns] = find(mask);
col1 = min(columns);
col2 = max(columns);
for col = col1 : col2
row2 = find(mask(:, col), 1, 'last');
if ~isempty(row2)
grayLevelSum(col) = sum(greenChannel(topRow:row2, col));
heights(col) = sum(mask(topRow:row2, col));
end
end
subplot(2, 3, 5);
plot(grayLevelSum, 'b-', 'LineWidth', 2);
xlabel('Column', 'FontSize', 20);
ylabel('Sum of gray levels in column', 'FontSize', 20);
title('Sum of gray levels in column', 'FontSize', 20);
grid on;
subplot(2, 3, 6);
plot(heights, 'b-', 'LineWidth', 2);
xlabel('Column', 'FontSize', 20);
ylabel('Height of mask in column', 'FontSize', 20);
title('Mask Height vs. Column', 'FontSize', 20);
grid on;
message = sprintf('Done!');
uiwait(helpdlg(message));
Best Answer