Download scripts/onnx_ocr.py from FlanChanXwO/phpwind-captcha-ocr: direct link, hf CLI and curl.
- Browser
- Download file 1.31 kB
-
https://huggingface.co/FlanChanXwO/phpwind-captcha-ocr/resolve/main/scripts/onnx_ocr.py
- Command line
-
hf download hf://FlanChanXwO/phpwind-captcha-ocr/scripts/onnx_ocr.py
-
curl -L -o onnx_ocr.py https://huggingface.co/FlanChanXwO/phpwind-captcha-ocr/resolve/main/scripts/onnx_ocr.py
1.31 kB
| #!/usr/bin/env python3 | |
| """用训练好的位置保留模型识别验证码。输出格式兼容 harness。 | |
| 预处理: 灰度->开运算去噪->RGB 160x64 /255 -> (1,3,64,160) -> (1,4,10) -> 4位数字 | |
| """ | |
| import json | |
| import os | |
| import sys | |
| import cv2 | |
| import numpy as np | |
| import onnxruntime as ort | |
| from PIL import Image | |
| MODEL = os.path.expanduser("~/sp_captcha_assets/models/captcha_1000.onnx") | |
| _sess = None | |
| def _get_sess(): | |
| global _sess | |
| if _sess is None: | |
| _sess = ort.InferenceSession(MODEL, providers=["CPUExecutionProvider"]) | |
| return _sess | |
| def predict(path): | |
| img = cv2.imread(path, cv2.IMREAD_GRAYSCALE) | |
| k = np.ones((2, 2), np.uint8) | |
| denoised = cv2.morphologyEx(img, cv2.MORPH_OPEN, k) | |
| im = Image.fromarray(denoised).convert("RGB").resize((160, 64), Image.BILINEAR) | |
| a = np.asarray(im, dtype=np.float32) / 255.0 | |
| x = a.transpose(2, 0, 1)[None] # (1,3,64,160) | |
| out = _get_sess().run(None, {"input": x})[0] # (1,4,10) | |
| return "".join(str(int(out[0, p].argmax())) for p in range(4)) | |
| def main(): | |
| out = {} | |
| for f in sys.argv[1:]: | |
| try: | |
| out[f] = {"onnx": predict(f)} | |
| except Exception as e: | |
| out[f] = {"onnx": "", "err": str(e)} | |
| print(json.dumps(out, ensure_ascii=False)) | |
| if __name__ == "__main__": | |
| main() | |