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

一、环境准备

  1. 安装 Perl
    大多数 Linux/macOS 系统已内置 Perl;

Windows 用户建议安装 Strawberry Perl。

  1. 安装 Tesseract OCR
    更多内容访问ttocr.com或联系1436423940

Ubuntu / Debian

sudo apt install tesseract-ocr

macOS

brew install tesseract
二、Perl 脚本编写
创建文件 captcha_ocr.pl:

!/usr/bin/perl

use strict;
use warnings;

获取命令行参数

my $image_path = shift or die "用法: perl captcha_ocr.pl <验证码图像路径>\n";

临时输出文件路径

my $output_file = "tmp_ocr_output";

构建并执行 Tesseract 命令

my $whitelist = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
my $cmd = "tesseract "$image_path" $output_file -l eng -c tessedit_char_whitelist=$whitelist 2>/dev/null";
system($cmd) == 0 or die "Tesseract 执行失败\n";

读取识别结果

open my $fh, '<', "$output_file.txt" or die "无法读取输出文件\n";
my $result = do { local $/; <$fh> };
close $fh;
unlink "$output_file.txt";

只保留大写字母和数字

$result =~ s/[^A-Z0-9]//g;

print "识别结果: $result\n";
赋予执行权限(Unix/macOS):

chmod +x captcha_ocr.pl
三、运行示例

perl captcha_ocr.pl ./code1.png
示例输出:

识别结果: 7FJK
四、功能拓展建议
功能 实现方式
批量识别图像 使用 opendir 遍历文件夹中的所有图像文件
日志保存 将结果写入日志或 CSV 文件中
图像增强 可结合 ImageMagick 做图像灰度化或去噪

示例批量识别框架:

opendir(my $dir, "./images") or die "无法打开文件夹";
while (my $file = readdir($dir)) {
next unless $file =~ /.png$/;
system("perl captcha_ocr.pl images/$file");
}
closedir($dir);

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