You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python实现验证码图片的数字提取功能?

验证码数字提取问题

我需要从验证码图片中提取数字,参考了相关回答的代码,代码如下:

try:
    from PIL import Image
except ImportError:
    import Image
import pytesseract
import cv2

file = 'sample.jpg'

img = cv2.imread(file, cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, None, fx=10, fy=10, interpolation=cv2.INTER_LINEAR)
img = cv2.medianBlur(img, 9)
th, img = cv2.threshold(img, 185, 255, cv2.THRESH_BINARY)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (4,8))
img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
cv2.imwrite("sample2.jpg", img)


file = 'sample2.jpg'
text = pytesseract.image_to_string(file)
print(''.join(x for x in text if x.isdigit()))

现有代码运行情况

  • 处理第一张示例验证码时运行正常:
    示例验证码1
    输出结果:outPut: 436359
  • 处理第二张示例验证码时无有效数字返回:
    示例验证码2
    输出结果:outPut:

问题1

请问我该如何修改代码,才能正确从第二张图片中提取数字字符串?

补充说明

我尝试了其他回答提供的方案,处理上述第二张图片时运行正常,但存在新的识别问题:无法正确识别图片A中的数字8、1,以及图片B中的数字7:
image A 图片A
image B 图片B

问题2

请问该识别问题如何修复?


内容的提问来源于stack exchange,提问作者Martin Wittick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 08:45:05