clc;
close all;
clear;
workspace;
format long g;
format compact;
fontSize = 20;
grayImage = imread('li.jpg');
subplot(3, 3, 1);
imshow(grayImage);
axis on;
[rows, columns, numberOfColorChannels] = size(grayImage);
if numberOfColorChannels > 1
grayImage = rgb2gray(grayImage);
end
grayImage = grayImage(321:472, 97:1104);
subplot(3, 3, 2);
imshow(grayImage);
axis on;
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
set(gcf, 'Toolbar', 'none', 'Menu', 'none');
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
[pixelCount, grayLevels] = imhist(grayImage);
subplot(3, 3, 3);
bar(grayLevels, pixelCount);
grid on;
title('Histogram of original image', 'FontSize', fontSize, 'Interpreter', 'None');
xlabel('Gray Level', 'FontSize', fontSize);
ylabel('Pixel Count', 'FontSize', fontSize);
xlim([0 grayLevels(end)]);
threshold = 200;
mask = grayImage > threshold;
mask = bwareaopen(mask, 50);
subplot(3, 3, 3);
imshow(mask);
axis on;
[labeledImage, numberOfRegions] = bwlabel(mask);
props = regionprops(labeledImage,'BoundingBox');
hold on
for n = 1 : numberOfRegions
rectangle('Position',props(n).BoundingBox, 'EdgeColor','r', 'LineWidth',2)
end
hold off
folder = 'C:\SegmentedCharacters';
for n = 1 : numberOfRegions
croppedImage = imcrop(mask, props(n).BoundingBox);
subplot(3, 3, n+3);
imshow(croppedImage);
axis on;
baseFileName = sprintf('figure %d.png', n);
fullFileName = fullfile(folder, baseFileName)
imwrite(croppedImage, fullFileName);
end
Best Answer