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

如何使用Python结合PIL分离3位验证码中的单个数字

验证码处理方案(背景变白+裁剪+分割)

1. 背景转为纯白色

先将图像转为灰度模式,通过阈值过滤把浅灰色背景替换为纯白色,保留深色数字:

# 转为灰度图
gray_im = im.convert('L')
# 阈值调整:根据验证码背景亮度设置,这里200适配你的验证码
threshold = 200
white_bg_im = gray_im.point(lambda x: 255 if x > threshold else x)

2. 裁剪多余空白区域

定位图像中所有非白色像素的边界,裁剪出仅包含验证码的有效区域:

pixels = white_bg_im.load()
width, height = white_bg_im.size

# 初始化边界值
left, right = width, 0
top, bottom = height, 0

# 遍历像素找有效区域边界
for x in range(width):
    for y in range(height):
        if pixels[x, y] != 255:
            left = min(left, x)
            right = max(right, x)
            top = min(top, y)
            bottom = max(bottom, y)

# 裁剪(注意right和bottom需+1,保证包含最后一个像素)
cropped_im = white_bg_im.crop((left, top, right + 1, bottom + 1))

3. 分割为单个数字图像

将裁剪后的图像按宽度三等分,得到三个独立的数字图像:

crop_width = cropped_im.width // 3

# 分别裁剪三个数字
digit1 = cropped_im.crop((0, 0, crop_width, cropped_im.height))
digit2 = cropped_im.crop((crop_width, 0, crop_width * 2, cropped_im.height))
digit3 = cropped_im.crop((crop_width * 2, 0, cropped_im.width, cropped_im.height))

# 保存结果(可选)
digit1.save('digit1.jpg')
digit2.save('digit2.jpg')
digit3.save('digit3.jpg')

完整代码

from PIL import Image

im = Image.open("captcha.jpg")

# 背景转纯白
gray_im = im.convert('L')
threshold = 200
white_bg_im = gray_im.point(lambda x: 255 if x > threshold else x)

# 裁剪空白
pixels = white_bg_im.load()
width, height = white_bg_im.size
left, right, top, bottom = width, 0, height, 0

for x in range(width):
    for y in range(height):
        if pixels[x, y] != 255:
            left = min(left, x)
            right = max(right, x)
            top = min(top, y)
            bottom = max(bottom, y)

cropped_im = white_bg_im.crop((left, top, right + 1, bottom + 1))

# 分割数字
crop_width = cropped_im.width // 3
digit1 = cropped_im.crop((0, 0, crop_width, cropped_im.height))
digit2 = cropped_im.crop((crop_width, 0, crop_width * 2, cropped_im.height))
digit3 = cropped_im.crop((crop_width * 2, 0, cropped_im.width, cropped_im.height))

# 保存分割后的图像
digit1.save('digit1.jpg')
digit2.save('digit2.jpg')
digit3.save('digit3.jpg')

内容的提问来源于stack exchange,提问作者ali emili

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 01:20:33