72 lines
2.5 KiB
Python
72 lines
2.5 KiB
Python
|
|
# coding=utf-8
|
||
|
|
# pip install easyocr
|
||
|
|
# python -m pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121 --force-reinstall
|
||
|
|
import os
|
||
|
|
import sys
|
||
|
|
import cv2
|
||
|
|
import numpy as np
|
||
|
|
# 设置项目根目录
|
||
|
|
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||
|
|
if project_root not in sys.path:
|
||
|
|
sys.path.append(project_root)
|
||
|
|
|
||
|
|
from Util.EasyOcrKit import get_easyocr_reader
|
||
|
|
|
||
|
|
def test_easyocr_price():
|
||
|
|
# 待测试的图片路径
|
||
|
|
test_image_path = os.path.join(project_root, "Output", "Screenshot_20260115_083521.jpg")
|
||
|
|
output_image_path = os.path.join(project_root, "Output", "Test_EasyOCR_Result.jpg")
|
||
|
|
|
||
|
|
print(f"--- 开始测试 EasyOCR 识别 ---")
|
||
|
|
print(f"输入图片: {test_image_path}")
|
||
|
|
|
||
|
|
if not os.path.exists(test_image_path):
|
||
|
|
print(f"错误: 测试图片不存在!")
|
||
|
|
return
|
||
|
|
|
||
|
|
# 1. 初始化 OCR (使用封装类)
|
||
|
|
reader = get_easyocr_reader(gpu=True)
|
||
|
|
|
||
|
|
# 2. 读取图片
|
||
|
|
img = cv2.imread(test_image_path)
|
||
|
|
if img is None:
|
||
|
|
print("错误: 无法读取图片。")
|
||
|
|
return
|
||
|
|
|
||
|
|
# 3. 识别
|
||
|
|
target = '全部时段'
|
||
|
|
found = reader.find_text_position(img, target)
|
||
|
|
|
||
|
|
h, w = img.shape[:2]
|
||
|
|
|
||
|
|
if found:
|
||
|
|
text, quad, prob = found
|
||
|
|
pts = np.array(quad).astype(int)
|
||
|
|
cv2.polylines(img, [pts], isClosed=True, color=(0, 255, 0), thickness=2)
|
||
|
|
|
||
|
|
# 使用封装后的方法获取归一化中心点 (演示 get_normalized_rect)
|
||
|
|
rect = reader.get_normalized_rect(quad, w, h)
|
||
|
|
norm_x = (rect[0] + rect[2]) // 2
|
||
|
|
norm_y = (rect[1] + rect[3]) // 2
|
||
|
|
|
||
|
|
print(f'找到“{text}” (目标: {target}) 置信度={prob:.2f}')
|
||
|
|
print(f'归一化坐标: [{norm_x}, {norm_y}]')
|
||
|
|
|
||
|
|
cv2.putText(img, f"OCR Found: {text}", (pts[0][0], pts[0][1] - 10),
|
||
|
|
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
|
||
|
|
else:
|
||
|
|
print(f"未能在图片中找到包含“{target}”的文本。")
|
||
|
|
# 打印出所有识别到的文本,方便调试
|
||
|
|
print("识别到的所有文本:")
|
||
|
|
results = reader.read_text(img)
|
||
|
|
for (_, text, _) in results:
|
||
|
|
print(f" - {text}")
|
||
|
|
|
||
|
|
# 4. 保存结果图
|
||
|
|
cv2.imwrite(output_image_path, img)
|
||
|
|
print(f"--- 测试完成 ---")
|
||
|
|
print(f"结果已保存至: {output_image_path}")
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
test_easyocr_price()
|