解决方案
clear
clc
BW1 = imread('alphabet.bmp');
patterns = bwlabel(~BW1);
patternStats = regionprops(patterns,'all');
patternNumber = size(patternStats);
imagePatternArray = cell(patternNumber);
for i = 1:1:patternNumber
imageMatrix = patternStats(i).Image;
imageMatrix = imresize(imageMatrix, [25 20]);
imagePatternArray{i} = imageMatrix;
end
BW2 = imread('kol_2.bmp');
BW2Gray = rgb2gray(BW2);
text = bwlabel(~BW2Gray);
textStats = regionprops(text,'all');
letterNumber = size(textStats);
imageLetterArray = cell(letterNumber);
for i = 1:1:letterNumber
imageMatrix = textStats(i).Image;
imageMatrix = imresize(imageMatrix, [25 20]);
imageLetterArray{i} = imageMatrix;
end
whiteSpacesIndexes = [];
for i = 1:letterNumber - 1
firstLetterBox = textStats(i).BoundingBox;
positionFirstVector = [firstLetterBox(1), firstLetterBox(2)];
secondLetterBox = textStats(i+1).BoundingBox;
positionSecondVector = [secondLetterBox(1), secondLetterBox(2)];
distanceVector = positionSecondVector - positionFirstVector;
distance = norm(distanceVector)
bothLettersSize = firstLetterBox(3) + secondLetterBox(3);
noSpaceDistance = bothLettersSize - bothLettersSize * 0.25;
if (distance > noSpaceDistance)
whiteSpacesIndexes = [whiteSpacesIndexes, i + 1];
end
end
compareVector = size(patternNumber);
indexArray = size(letterNumber);
for i = 1:1:letterNumber
for j = 1:1:patternNumber
correlationMatrix = normxcorr2(imagePatternArray{j},imageLetterArray{i});
compareVector(j) = max(abs(correlationMatrix(:)));
end
[correlationMax,correlationIndex] = max(compareVector);
indexArray(i) = correlationIndex;
end
charSet = ['A','B','C','D','E','F','G','H','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
outPut = size(letterNumber);
for i = 1:1:letterNumber
outPut(i) = charSet(indexArray(i));
end
whiteSpaceNumber = size(whiteSpacesIndexes,2);
whiteSpacesIndexes = whiteSpacesIndexes + (0:numel(whiteSpacesIndexes)-1)
nFinal = numel(outPut)+numel(whiteSpacesIndexes );
newstr = blanks(nFinal);
newstr(setdiff(1:nFinal,whiteSpacesIndexes )) = outPut
我很简单,但有一些缺点,比如:
- 不能读取“我”
- 只能读取水平的文本条
- 白色空间检测需要改进