clc;
close all;
imtool close all;
clear;
workspace;
format long g;
format compact;
fontSize = 22;
hasIPT = license('test', 'image_toolbox');
if ~hasIPT
message = sprintf('Sorry, but you do not seem to have the Image Processing Toolbox.\nDo you want to try to continue anyway?');
reply = questdlg(message, 'Toolbox missing', 'Yes', 'No', 'Yes');
if strcmpi(reply, 'No')
return;
end
end
folder = pwd;
baseFileName = 'find_gaps.png';
fullFileName = fullfile(folder, baseFileName);
if ~exist(fullFileName, 'file')
fullFileName = baseFileName;
if ~exist(fullFileName, 'file')
errorMessage = sprintf('Error: %s does not exist.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
grayImage = imread(fullFileName);
[rows, columns, numberOfColorBands] = size(grayImage);
if numberOfColorBands > 1
fprintf('This image is RGB. I will change it to binary.\n');
grayImage = grayImage(:, :, 2);
end
binaryImage = grayImage > 128;
clear('grayImage');
subplot(2, 2, 1);
imshow(binaryImage);
axis('on', 'image');
title('Binary Image', 'FontSize', fontSize);
impixelinfo;
set(gcf, 'Units', 'Normalized', 'Outerposition', [0, 0.1, 1, 0.9]);
se = true(3);
binaryImage2 = imclose(binaryImage, se);
subplot(2, 2, 2);
imshow(binaryImage2, []);
axis('on', 'image');
title('Closing', 'FontSize', fontSize);
binaryImage2 = xor(binaryImage, binaryImage2);
[labeledImage, numRegions] = bwlabel(binaryImage2);
coloredLabels = label2rgb (labeledImage, 'hsv', 'k', 'shuffle');
subplot(2, 2, 3);
imshow(coloredLabels, []);
axis('on', 'image');
caption = sprintf('XOR Found %d Lines', numRegions);
title(caption, 'FontSize', fontSize);
props = regionprops(labeledImage, 'Area', 'Centroid');
[allAreas, sortOrder] = sort([props.Area], 'Descend');
props = props(sortOrder);
subplot(2, 2, 4);
imshow(binaryImage);
axis('on', 'image');
title('Line Centroids Marked with *', 'FontSize', fontSize);
hold on;
for k = 1 : length(props)
x = props(k).Centroid(1);
y = props(k).Centroid(2);
plot(x, y, 'r*', 'MarkerSize', 15, 'LineWidth', 2);
fprintf('Blob #%d is at (%.1f, %.1f) and has length %d.\n', ...
k, x, y, allAreas(k));
end
Best Answer