遇到一个验证码。如图:


想着自己生成一批,用ddddocr_trainer去训练一下。用cursor写了个代码,但是练出来后效果很差。有佬指点一下吗?
爬下来的验证码:
手动生成验证码的代码:
import random
from PIL import Image, ImageDraw, ImageFont
# 设置图像尺寸
width = 32
height = 24
# 创建新图像,黑底
image = Image.new("RGB", (width, height), "black")
draw = ImageDraw.Draw(image)
# 加载字体
font_size = 16 # 保持原字体大小,但噪点排除区域按8x8处理
font = ImageFont.truetype("font/typostuck.ttf", font_size)
# 生成4个随机字符(A-Z 和 1-9,不包含0)
chars = [random.choice("BCEFGHKMORTVXY2346789") for _ in range(4)]
# 设置字符位置和y偏移
x_positions = [0, 8, 17, 26] # x位置:0, 8, 16, 24
y_offsets = [random.randint(-2, 2) for _ in range(4)] # 随机y偏移
# 在图像上绘制字符(白字)
base_y = (height - 8) // 2 # 中心8x8区域,base_y = (24 - 8) // 2 = 8
for x, char, y_offset in zip(x_positions, chars, y_offsets):
y = base_y + y_offset
draw.text((x, y), char, font=font, fill="white")
# 定义噪点参数
noise_density = 0.5 # 噪点密度为80%
gap_x = {6, 7, 14, 15, 22, 23} # 2像素间隙的x坐标
# 定义8x8噪点排除区域
noise_free_regions = []
for x_position, y_offset in zip(x_positions, y_offsets):
x_start = x_position
x_end = x_position + 10
y_start = base_y + y_offset
y_end = y_start + 10
noise_free_regions.append({
'x_range': (x_start, x_end),
'y_range': (y_start, y_end)
})
# 计算所有可放置噪点的像素
total_noise_pixels = 0
valid_pixels = []
for x in range(width):
if x in gap_x: # 排除2像素间隙
continue
for y in range(height):
is_noise_free = False
for region in noise_free_regions:
x_start, x_end = region['x_range']
y_start, y_end = region['y_range']
if x_start <= x < x_end and y_start <= y < y_end:
is_noise_free = True
break
if not is_noise_free:
valid_pixels.append((x, y))
total_noise_pixels += 1
# 计算噪点数量
num_noise_pixels = int(total_noise_pixels * noise_density)
# 添加噪点
for _ in range(num_noise_pixels):
if valid_pixels:
x, y = random.choice(valid_pixels)
draw.point((x, y), fill="white")
# 保存图像
image.save("captcha.png")
ddddocr_trainer的训练参数:
Model:
CharSet: [' ', '3', '6', K, V, '7', H, M, '5', B, F, O, Y, '4', '9', X, '2', C,
G, E, '8', W, T, R]
ImageChannel: 1
ImageHeight: 64
ImageWidth: -1
Word: false
System:
Allow_Ext: [jpg, jpeg, png, bmp]
GPU: true
GPU_ID: 0
Path: captchas/
Project: captcha_1m
Val: 0.005
Train:
BATCH_SIZE: 512
CNN: {NAME: ddddocr}
DROPOUT: 0.25
LR: 0.002
OPTIMIZER: Adam
SAVE_CHECKPOINTS_STEP: 20000
TARGET: {Accuracy: 0.999, Cost: 0.001, Epoch: 2}
TEST_BATCH_SIZE: 512
TEST_STEP: 10000