image_ocr_test.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import requests
  2. import os
  3. import sys
  4. def test_ocr_service(image_path, server_url="http://127.0.0.1:8085/predict/vfcode"):
  5. """
  6. 读取本地图片并发送给 OCR 服务进行识别
  7. """
  8. # 1. 检查文件是否存在
  9. if not os.path.exists(image_path):
  10. print(f"[错误] 找不到文件: {image_path}")
  11. return
  12. print(f"[INFO] 正在读取图片: {image_path}")
  13. print(f"[INFO] 目标服务器: {server_url}")
  14. try:
  15. # 2. 读取图片二进制数据
  16. with open(image_path, 'rb') as f:
  17. image_data = f.read()
  18. # 3. 发送 POST 请求
  19. # 注意:这里直接发送二进制流 (data=image_data),配合之前的 predict_server.py 使用
  20. # 如果服务端要求 multipart/form-data,则需要用 files={'file': f}
  21. start_time = time.time()
  22. response = requests.post(
  23. server_url,
  24. data=image_data,
  25. headers={"Content-Type": "application/octet-stream"}, # 标识为二进制流
  26. timeout=10
  27. )
  28. cost_time = (time.time() - start_time) * 1000
  29. # 4. 解析响应
  30. if response.status_code == 200:
  31. result = response.json()
  32. ocr_text = result.get('data', '').replace('$', '') # 去除可能存在的结束符
  33. print("-" * 40)
  34. print(f"✅ 识别成功")
  35. print(f"📸 结果: {ocr_text}")
  36. print(f"⏱️ 耗时: {cost_time:.2f} ms")
  37. print(f"📩 原始响应: {result}")
  38. print("-" * 40)
  39. else:
  40. print(f"[失败] 服务器返回状态码: {response.status_code}")
  41. print(f"响应内容: {response.text}")
  42. except requests.exceptions.ConnectionError:
  43. print("[错误] 无法连接到服务器。请确认 predict_server.py 正在运行且端口正确。")
  44. except Exception as e:
  45. print(f"[错误] 发生异常: {e}")
  46. if __name__ == "__main__":
  47. import time
  48. # --- 配置 ---
  49. SERVER_URL = "http://127.0.0.1:8085/predict/vfcode"
  50. # 默认测试图片路径 (请修改为你本地实际存在的验证码图片路径)
  51. # 你可以放一张图片在当前目录下,命名为 test.jpg
  52. DEFAULT_IMAGE = "output.png"
  53. # 支持命令行参数: python test_ocr_client.py my_image.png
  54. if len(sys.argv) > 1:
  55. image_file = sys.argv[1]
  56. else:
  57. image_file = DEFAULT_IMAGE
  58. # 如果默认图片不存在,尝试在 test 目录下找一个
  59. if not os.path.exists(image_file):
  60. if os.path.exists("test/562_xxxx.gif"): # 假设你的项目结构里有这个
  61. image_file = "test/562_xxxx.gif"
  62. elif os.path.exists("data/captcha.jpg"):
  63. image_file = "data/captcha.jpg"
  64. # 开始测试
  65. test_ocr_service(image_file, SERVER_URL)