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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""训练南+定长4位数字验证码分类器,导出 ONNX。
|
| 3 |
+
模型: CNN 骨干 + 4 个位置头,每头 10 类(0-9)。
|
| 4 |
+
输入 (1,1,64,160) 灰度/255,输出 (B,4,10) logits。
|
| 5 |
+
用法: train_fixed.py <labels.json> <图片目录> <输出.onnx> [val_frac] [epochs]
|
| 6 |
+
"""
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import random
|
| 10 |
+
import sys
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn as nn
|
| 15 |
+
from PIL import Image
|
| 16 |
+
|
| 17 |
+
W, H = 160, 64
|
| 18 |
+
NDIGITS = 4
|
| 19 |
+
RGB = "rgb" in sys.argv
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class Dataset:
|
| 23 |
+
def __init__(self, items, aug=False):
|
| 24 |
+
self.items = items
|
| 25 |
+
self.aug = aug
|
| 26 |
+
|
| 27 |
+
def __len__(self):
|
| 28 |
+
return len(self.items)
|
| 29 |
+
|
| 30 |
+
def __getitem__(self, i):
|
| 31 |
+
path, lbl = self.items[i]
|
| 32 |
+
mode = "RGB" if RGB else "L"
|
| 33 |
+
im = Image.open(path).convert(mode).resize((W, H), Image.BILINEAR)
|
| 34 |
+
if self.aug:
|
| 35 |
+
im = augment(im)
|
| 36 |
+
a = np.asarray(im, dtype=np.float32) / 255.0
|
| 37 |
+
if RGB:
|
| 38 |
+
x = torch.from_numpy(a).permute(2, 0, 1) # (C,H,W)
|
| 39 |
+
else:
|
| 40 |
+
x = torch.from_numpy(a).unsqueeze(0)
|
| 41 |
+
t = torch.tensor([int(c) for c in lbl], dtype=torch.long)
|
| 42 |
+
return x, t
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def augment(im):
|
| 46 |
+
import random as R
|
| 47 |
+
from PIL import Image
|
| 48 |
+
if R.random() < 0.8:
|
| 49 |
+
im = im.rotate(R.uniform(-6, 6), resample=Image.BILINEAR, fillcolor=255)
|
| 50 |
+
scale = R.uniform(0.92, 1.08)
|
| 51 |
+
tx, ty = R.uniform(-3, 3), R.uniform(-2, 2)
|
| 52 |
+
w, h = im.size
|
| 53 |
+
a, b, c, d, e, f = (scale, 0, -w * scale / 2 + w / 2 + tx,
|
| 54 |
+
0, scale, -h * scale / 2 + h / 2 + ty)
|
| 55 |
+
im = im.transform((w, h), Image.AFFINE, (a, b, c, d, e, f),
|
| 56 |
+
resample=Image.BILINEAR, fillcolor=255)
|
| 57 |
+
# 可选轻微噪声(默认关,避免盖掉验证码原有干扰线)
|
| 58 |
+
if os.environ.get("AUG_NOISE", "0") == "1":
|
| 59 |
+
arr = np.asarray(im, dtype=np.float32)
|
| 60 |
+
arr += np.random.normal(0, 5, arr.shape)
|
| 61 |
+
return Image.fromarray(np.clip(arr, 0, 255).astype(np.uint8), im.mode)
|
| 62 |
+
return im
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class FixedNet(nn.Module):
|
| 66 |
+
def __init__(self):
|
| 67 |
+
super().__init__()
|
| 68 |
+
in_ch = 3 if RGB else 1
|
| 69 |
+
self.features = nn.Sequential(
|
| 70 |
+
nn.Conv2d(in_ch, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.MaxPool2d(2),
|
| 71 |
+
nn.Conv2d(32, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(2),
|
| 72 |
+
nn.Conv2d(64, 128, 3, padding=1), nn.BatchNorm2d(128), nn.ReLU(), nn.MaxPool2d(2),
|
| 73 |
+
nn.Conv2d(128, 256, 3, padding=1), nn.BatchNorm2d(256), nn.ReLU(),
|
| 74 |
+
nn.Conv2d(256, 256, 3, padding=1), nn.BatchNorm2d(256), nn.ReLU(),
|
| 75 |
+
)
|
| 76 |
+
# 保留空间位置:20列特征按4个数字位置各池化
|
| 77 |
+
self.heads = nn.ModuleList([nn.Linear(256, 10) for _ in range(NDIGITS)])
|
| 78 |
+
|
| 79 |
+
def forward(self, x):
|
| 80 |
+
x = self.features(x) # (B,256,8,20)
|
| 81 |
+
x = x.mean(dim=2) # 高度池化 (B,256,20)
|
| 82 |
+
# 20列 -> 4个位置(每位置5列),保持左右顺序
|
| 83 |
+
B, C, T = x.shape
|
| 84 |
+
per = T // NDIGITS
|
| 85 |
+
x = x.view(B, C, NDIGITS, per).mean(dim=3) # (B,256,4)
|
| 86 |
+
x = x.permute(0, 2, 1) # (B,4,256)
|
| 87 |
+
return torch.stack([self.heads[p](x[:, p]) for p in range(NDIGITS)], dim=1) # (B,4,10)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def collate(batch):
|
| 91 |
+
xs = torch.stack([b[0] for b in batch])
|
| 92 |
+
ts = torch.stack([b[1] for b in batch])
|
| 93 |
+
return xs, ts
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def main():
|
| 97 |
+
labels = json.load(open(sys.argv[1]))
|
| 98 |
+
imgdir = sys.argv[2]
|
| 99 |
+
out = sys.argv[3] if len(sys.argv) > 3 else "/tmp/sp_captest/captcha_fixed.onnx"
|
| 100 |
+
val_frac = float(sys.argv[4]) if len(sys.argv) > 4 else 0.1
|
| 101 |
+
epochs = int(sys.argv[5]) if len(sys.argv) > 5 else 400
|
| 102 |
+
use_aug = sys.argv[6] != "0" if len(sys.argv) > 6 else True
|
| 103 |
+
|
| 104 |
+
all_items = [(f"{imgdir}/{fn}", v["label"]) for fn, v in labels.items()
|
| 105 |
+
if v.get("label") and len(v["label"]) == NDIGITS]
|
| 106 |
+
random.Random(42).shuffle(all_items)
|
| 107 |
+
n_val = int(len(all_items) * val_frac)
|
| 108 |
+
train_ds = Dataset(all_items[n_val:], aug=use_aug)
|
| 109 |
+
val_ds = Dataset(all_items[:n_val], aug=False)
|
| 110 |
+
tr = torch.utils.data.DataLoader(train_ds, batch_size=16, shuffle=True, collate_fn=collate)
|
| 111 |
+
va = torch.utils.data.DataLoader(val_ds, batch_size=16, shuffle=False, collate_fn=collate)
|
| 112 |
+
print(f"train={len(train_ds)} val={len(val_ds)} total={len(all_items)}")
|
| 113 |
+
|
| 114 |
+
device = "cpu"
|
| 115 |
+
model = FixedNet().to(device)
|
| 116 |
+
# 断点续训: 从已有 checkpoint 加载权重
|
| 117 |
+
resume_pt = out + ".pt"
|
| 118 |
+
start_ep = 0
|
| 119 |
+
if os.path.exists(resume_pt):
|
| 120 |
+
model.load_state_dict(torch.load(resume_pt))
|
| 121 |
+
start_ep = int(sys.argv[7]) if len(sys.argv) > 7 else 0
|
| 122 |
+
print(f"从 checkpoint 续训, 起始 epoch={start_ep}")
|
| 123 |
+
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
|
| 124 |
+
sched = torch.optim.lr_scheduler.ReduceLROnPlateau(opt, factor=0.5, patience=10)
|
| 125 |
+
crit = nn.CrossEntropyLoss()
|
| 126 |
+
|
| 127 |
+
best = 0.0
|
| 128 |
+
for ep in range(start_ep, start_ep + epochs):
|
| 129 |
+
model.train()
|
| 130 |
+
tot = 0.0
|
| 131 |
+
for x, t in tr:
|
| 132 |
+
x, t = x.to(device), t.to(device)
|
| 133 |
+
logits = model(x) # (B,4,10)
|
| 134 |
+
loss = sum(crit(logits[:, p], t[:, p]) for p in range(NDIGITS))
|
| 135 |
+
opt.zero_grad(); loss.backward(); opt.step()
|
| 136 |
+
tot += loss.item() * x.size(0)
|
| 137 |
+
model.eval()
|
| 138 |
+
acc = n = 0
|
| 139 |
+
with torch.no_grad():
|
| 140 |
+
for x, t in va:
|
| 141 |
+
p = model(x).argmax(-1) # (B,4)
|
| 142 |
+
acc += (p == t).all(dim=1).sum().item()
|
| 143 |
+
n += x.size(0)
|
| 144 |
+
acc /= max(1, n)
|
| 145 |
+
sched.step(acc)
|
| 146 |
+
if acc > best:
|
| 147 |
+
best = acc
|
| 148 |
+
torch.save(model.state_dict(), out + ".pt")
|
| 149 |
+
if ep % 10 == 0 or ep == epochs - 1:
|
| 150 |
+
print(f"epoch {ep} loss={tot/len(train_ds):.3f} val_acc={acc:.2%} best={best:.2%}", flush=True)
|
| 151 |
+
if not os.path.exists(out + ".pt"): # 从未有更好验证精度时,保存最后权重
|
| 152 |
+
torch.save(model.state_dict(), out + ".pt")
|
| 153 |
+
print(f"DONE best_val_acc={best:.2%}")
|
| 154 |
+
|
| 155 |
+
model.load_state_dict(torch.load(out + ".pt"))
|
| 156 |
+
model.eval()
|
| 157 |
+
dummy = torch.randn(1, 3 if RGB else 1, H, W)
|
| 158 |
+
torch.onnx.export(model, dummy, out,
|
| 159 |
+
input_names=["input"], output_names=["logits"],
|
| 160 |
+
dynamic_axes={"input": {0: "batch"}, "logits": {0: "batch"}},
|
| 161 |
+
opset_version=13, external_data=False)
|
| 162 |
+
print(f"ONNX exported -> {out}")
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
if __name__ == "__main__":
|
| 166 |
+
main()
|