Upload scripts/onnx_ocr.py with huggingface_hub
Browse files- scripts/onnx_ocr.py +47 -3
scripts/onnx_ocr.py
CHANGED
|
@@ -1,3 +1,47 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""用训练好的位置保留模型识别验证码。输出格式兼容 harness。
|
| 3 |
+
预处理: 灰度->开运算去噪->RGB 160x64 /255 -> (1,3,64,160) -> (1,4,10) -> 4位数字
|
| 4 |
+
"""
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
|
| 9 |
+
import cv2
|
| 10 |
+
import numpy as np
|
| 11 |
+
import onnxruntime as ort
|
| 12 |
+
from PIL import Image
|
| 13 |
+
|
| 14 |
+
MODEL = os.path.expanduser("~/sp_captcha_assets/models/captcha_1000.onnx")
|
| 15 |
+
_sess = None
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _get_sess():
|
| 19 |
+
global _sess
|
| 20 |
+
if _sess is None:
|
| 21 |
+
_sess = ort.InferenceSession(MODEL, providers=["CPUExecutionProvider"])
|
| 22 |
+
return _sess
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def predict(path):
|
| 26 |
+
img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
|
| 27 |
+
k = np.ones((2, 2), np.uint8)
|
| 28 |
+
denoised = cv2.morphologyEx(img, cv2.MORPH_OPEN, k)
|
| 29 |
+
im = Image.fromarray(denoised).convert("RGB").resize((160, 64), Image.BILINEAR)
|
| 30 |
+
a = np.asarray(im, dtype=np.float32) / 255.0
|
| 31 |
+
x = a.transpose(2, 0, 1)[None] # (1,3,64,160)
|
| 32 |
+
out = _get_sess().run(None, {"input": x})[0] # (1,4,10)
|
| 33 |
+
return "".join(str(int(out[0, p].argmax())) for p in range(4))
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def main():
|
| 37 |
+
out = {}
|
| 38 |
+
for f in sys.argv[1:]:
|
| 39 |
+
try:
|
| 40 |
+
out[f] = {"onnx": predict(f)}
|
| 41 |
+
except Exception as e:
|
| 42 |
+
out[f] = {"onnx": "", "err": str(e)}
|
| 43 |
+
print(json.dumps(out, ensure_ascii=False))
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
if __name__ == "__main__":
|
| 47 |
+
main()
|