如何从图像中提取文字中的文字?

问题描述 投票:1回答:1

我试图从打印文本的图像中提取文本。除了文本本身,我也有兴趣检测单词之间的空格。单词之间的空格不一致(故意),这是我想要检测到的。

为了达到这个目的,我首先要提取文本行。我使用附加的投影配置文件代码实现了这一点(从ImageAnalyst的一个答案复制的代码)。 enter image description here

我想到实现这一目标的一种方法是计算单词之间的白色像素数,如果我知道单个空格(比如n)所占的像素数,我可以通过将白色像素之间的白色像素分开来确定空格的数量。这个'n'的单词得到空格的数量。

我试过了,但它没有按计划进行,结果非常矛盾,即使与已知的地面实况值进行比较也是如此。确定每个文本行的基线证明是困难的,因为对于两个单词之间的单个空格,我得到不同的像素数。这是因为从字母d到b计算白色像素与从c到s计算白色像素不同(有时也计算c曲线内的白色像素。)

任何指导或建议将不胜感激。

谢谢

我使用的代码:

clc;  
close all;  
clear;  
fontSize = 16; 
img = imread('Lines.png');

[rows, columns, dim] = size(img);
if dim > 1  
    grayImage = img(:, :, 2);
end

% Display the original gray scale image.
subplot(3, 3, 1);
imshow(grayImage, []);
title('Original image', 'FontSize', fontSize);
axis on;

set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]); % Enlarge figure to full screen.

% Threshold the image.
binaryImage = grayImage < 210;  

% Get rid of small areaas of 14 pixels or less
binaryImage = ~bwareaopen(binaryImage, 15);
subplot(2, 3, 2);
imshow(binaryImage);
title('Binary Image', 'FontSize', fontSize);
axis on;

% Vertical Profile
verticalProfile = sum(binaryImage, 2); 
subplot(3, 3, [2 3]);
plot(verticalProfile, 'b');
grid on;
title('Vertical Profile', 'FontSize', fontSize);

rowsWithText = verticalProfile < 600;  

% Find top and bottom lines
topLines = find(diff(rowsWithText) == 1);
bottomLines = find(diff(rowsWithText) == -1);

for j = 1 : length(topLines) 
    topRow = topLines(j);
    bottomRow = bottomLines(j);
    thisLine = binaryImage(topRow:bottomRow, :);
    subplot(3, 3, [4 5 6]);
    imshow(thisLine, []);
    axis on;
    caption = sprintf('Line %d of the text', j);
    title(caption, 'FontSize', fontSize);

    % Horizontal profile
    horizontalProfile = sum(thisLine, 1);
    subplot(3, 3, [7 8 9]);
    plot(horizontalProfile);
    grid on;
    caption = sprintf('Horizontal Profile of Line %d of the text', j);
    title(caption, 'FontSize', fontSize);

    promptMessage = sprintf('lines %d', j);
    titleBarCaption = 'Continue?';
    button = questdlg(promptMessage, titleBarCaption, 'Continue', 'Cancel', 'Continue');
    if strcmpi(button, 'Cancel')
        return;
    end  
end
msgbox('Done!');

图片:Image of my program

matlab image-processing
1个回答
1
投票

试着玩这样的东西:

% define min length of gap between words; play around with this value
min_gap_length = 5;

% define wordStarts/wordEnds like you've defined topLines/bottomLines
wordStarts = find(diff(horizontalProfile) == -1);
wordEnds = find(diff(horizontalProfile) == 1);
if wordStarts(1) > wordEnds(1)
    wordStarts = [1, wordStarts];
end
if wordEnds(end) < wordStarts(end)
    wordEnds = [wordEnds, length(horizontalProfile)];
end

% restrict wordStarts/wordEnds to gaps of over min_gap_length
I = wordStarts(2:end) - wordEnds(1:end-1) > min_gap_length;
wordStarts = wordStarts([true, I]);
wordEnds = wordEnds([I, true]);
© www.soinside.com 2019 - 2024. All rights reserved.