使用 Matlab 与 Tesseract 实现验证码识别

一、环境准备

  1. 安装 Matlab
    可从官网或所在学校/单位下载安装。

  2. 安装 Tesseract OCR
    Windows:安装时勾选“Add to PATH”
    更多内容访问ttocr.com或联系1436423940

macOS:brew install tesseract

Linux:sudo apt install tesseract-ocr

二、图像识别脚本
创建 captcha_ocr.m 脚本文件:

function captcha_ocr(imagePath)
if ~isfile(imagePath)
fprintf('找不到文件:%s\n', imagePath);
return;
end

% 构建命令
outputTxt = [tempname, '.txt'];
whitelist = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
command = sprintf('tesseract "%s" "%s" -l eng -c tessedit_char_whitelist=%s', ...
                  imagePath, outputTxt(1:end-4), whitelist);

status = system(command);

if status ~= 0
    fprintf('执行 Tesseract 出错。\n');
    return;
end

% 读取识别结果
fid = fopen(outputTxt, 'r');
if fid == -1
    fprintf('无法读取识别结果文件。\n');
    return;
end

result = fscanf(fid, '%c');
fclose(fid);
delete(outputTxt);  % 清理临时文件

% 保留大写字母与数字
resultClean = regexprep(result, '[^A-Z0-9]', '');
fprintf('识别结果: %s\n', resultClean);

end
三、运行示例
在 Matlab 命令窗口中运行:

captcha_ocr('code1.png')
示例输出:

识别结果: B5XQ
四、图像预处理建议(可选)
为提升准确率,可以预先处理图像:

img = imread('code1.png');
gray = rgb2gray(img);
bw = imbinarize(gray);
imwrite(bw, 'processed.png');
captcha_ocr('processed.png');

posted @ 2025-06-26 12:17  ttocr、com  阅读(41)  评论(0)    收藏  举报