使用VBA Excel与Tesseract提取图片文本失败求助
VBA调用Tesseract提取图片文本无输出问题排查与解决
原代码核心问题
- 命令参数传递错误:原代码错误地将Tesseract命令作为powershell的参数传递,格式混乱导致命令未正确执行。
- 引号使用错误:命令中多余的单引号导致Tesseract无法识别输入输出路径和语言参数。
- 缺乏错误检查:未验证文本文件是否生成,无法定位命令执行失败的原因。
修正后的代码
Sub ExtractTextFromImage() Dim myshell As Shell32.Shell Dim tesseractPath As String Dim inputImagePath As String Dim outputTextPath As String Dim readCommand As String Dim captchaCode As String Dim i As Integer ' 根据Tesseract版本选择对应路径 tesseractPath = "C:\Program Files\Tesseract-OCR\tesseract.exe" ' 64位版本 ' tesseractPath = "C:\Program Files (x86)\Tesseract-OCR\tesseract.exe" ' 32位版本 inputImagePath = "C:\Temp\Sem.png" outputTextPath = "C:\Temp\Sem" ' Tesseract会自动添加.txt后缀 Set myshell = New Shell32.Shell For i = 1 To 5 ' 构建格式正确的命令:路径用双引号包裹,参数无多余引号 readCommand = """" & tesseractPath & """ """ & inputImagePath & """ """ & outputTextPath & """ -l eng" ' 通过cmd执行命令,vShow=1可显示窗口用于调试 myshell.ShellExecute "cmd.exe", "/c " & readCommand, , "open", 1 ' 等待命令执行完成(根据图片复杂度调整时长) Application.Wait Now + TimeValue("00:00:03") ' 检查输出文件是否存在 If Dir(outputTextPath & ".txt") <> "" Then Open outputTextPath & ".txt" For Input As #1 Line Input #1, captchaCode Close #1 ' 清理文本中的无效字符并写入单元格 captchaCode = Application.WorksheetFunction.Clean(Trim(captchaCode)) Cells(i + 1, 2).Value = captchaCode Cells(i + 1, 1).Value = "Sr. " & i Else Cells(i + 1, 2).Value = "提取失败:文本文件未生成" End If Next i Set myshell = Nothing End Sub
额外排查步骤
- 手动验证Tesseract功能:打开命令提示符,执行以下命令测试:
若手动执行也无法生成正确文本,说明图片本身存在问题(如分辨率低、文字模糊、字体特殊),需对图片进行预处理(调高对比度、放大分辨率)。"C:\Program Files\Tesseract-OCR\tesseract.exe" "C:\Temp\Sem.png" "C:\Temp\Sem" -l eng - 权限与路径检查:确保
C:\Temp文件夹有读写权限,路径拼写无错误。 - 64位环境适配:若使用64位Excel,确认已正确引用64位版本的
Microsoft Shell Controls and Automation组件,或改用ShellExecuteAPI调用替代控件引用。
内容的提问来源于stack exchange,提问作者Gutemberg Silveira Alves GTTJ
相关产品推荐
相关产品推荐

