基于MATLAB实现图片文字识别并输出为TXT文件
基于MATLAB实现图片文字识别并输出为TXT文件
一、核心实现流程
% 步骤1:读取图像并预处理
img = imread('test_image.jpg');
grayImg = rgb2gray(img); % 灰度化
bwImg = imbinarize(grayImg, 'adaptive', 'Sensitivity', 0.6); % 自适应二值化
cleanImg = bwareaopen(bwImg, 50); % 去噪
% 步骤2:文本检测(CRAFT深度学习模型)
[bboxes, scores] = detectTextCRAFT(cleanImg); % 检测文本区域
cleanedBboxes = mergeTextRegions(bboxes, scores); % 合并重叠区域
% 步骤3:字符分割
characters = segmentCharacters(cleanImg, cleanedBboxes); % 基于连通域分割
% 步骤4:文字识别
recognizedText = '';
for i = 1:numel(characters)
charImg = imresize(characters{i}, [40, 30]); % 标准化尺寸
ocrResults = ocr(charImg, 'Language', 'English+Chinese'); % 多语言识别
recognizedText = [recognizedText, ocrResults.Text];
end
% 步骤5:保存结果
fid = fopen('output.txt', 'w');
fprintf(fid, '%s', recognizedText);
fclose(fid);
二、关键模块详解
1. 图像预处理优化
function processedImg = advancedPreprocess(img)
% 自动对比度增强
enhanced = adapthisteq(img, 'ClipLimit', 0.02); % CLAHE算法
% 倾斜校正
[theta, rho] = hough(enhanced);
peaks = houghpeaks(rho, theta, 1);
lines = houghlines(enhanced, theta, rho, peaks);
angle = mean([lines(theta>0).theta]);
rotated = imrotate(enhanced, -angle, 'crop');
% 多尺度增强
pyramid = imagePyramid(rotated, 'Scale', 1.5);
processedImg = imresize(pyramid{2}, size(rotated));
end
2. 文本区域检测(CRAFT模型)
% 加载预训练模型
if isempty(gcp('nocreate'))
parpool; % 启动并行池加速
end
net = load('craft_text_detection.mat'); % 下载预训练模型
% 检测函数
function bboxes = detectTextCRAFT(I)
inputSize = [32, 128, 3];
augmentedImg = imresize(I, inputSize(1:2));
data = augmentedImg(:,:,:,1);
bboxes = detect(net, data);
end
3. 字符分割算法
function chars = segmentCharacters(bwImg, bboxes)
chars = {};
for i = 1:size(bboxes,1)
roi = imcrop(bwImg, bboxes(i,:));
stats = regionprops(roi, 'BoundingBox');
for j = 1:numel(stats)
charBbox = stats(j).BoundingBox;
charImg = imresize(imcrop(roi, charBbox), [40,40]);
chars{end+1} = charImg;
end
end
end
三、完整应用案例
工业仪表读数识别
function readInstrument(imgPath)
% 预处理
img = imread(imgPath);
processed = advancedPreprocess(img);
% 区域定位(仪表盘ROI)
roi = [100, 200, 50, 80]; % 根据实际仪表调整坐标
digitImg = imcrop(processed, roi);
% 数字识别
digits = detectNumbers(digitImg);
result = num2str(digits);
% 输出结果
fid = fopen('instrument_read.txt', 'w');
fprintf(fid, '仪表读数:%s', result);
fclose(fid);
end
参考代码 识别图片中的文字,转化为txt www.youwenfan.com/contentcno/96148.html
四、结果验证与调试
-
可视化调试
function visualizeProcessing(img) figure; subplot(2,2,1); imshow(img); title('原图'); subplot(2,2,2); imshow(preprocessedImg); title('预处理'); subplot(2,2,3); imshow(bboxes); title('文本区域'); subplot(2,2,4); imshow(recognizedText); title('识别结果'); end -
错误分析
function errorAnalysis(groundTruth, ocrResult) confMat = confusionmat(groundTruth, ocrResult); figure; confusionchart(confMat); title('字符识别混淆矩阵'); end
五、扩展功能建议
-
批量处理
function batchProcess(folderPath) files = dir(fullfile(folderPath, '*.jpg')); for i = 1:numel(files) processImage(fullfile(folderPath, files(i).name)); end end -
Web服务部署
webApp = matlab.web.app.ServerApp; webApp.addSourceFiles('app.m'); webApp.start();
六、注意事项
- 环境配置 安装Computer Vision Toolbox和Deep Learning Toolbox 下载CRAFT预训练模型(需MATLAB R2022a+)
- 性能瓶颈 大尺寸图像建议先降采样(imresize) 使用parfor实现并行计算加速
七、参考文献
- 基于模板匹配的OCR实现(CSDN博客)
- MATLAB图像文字识别优化指南
- CRAFT文本检测模型使用说明
- 字符分割与匹配算法实现
浙公网安备 33010602011771号