Files
douyin_guaji-main/deleted_tests_backup/test_ocr_speed.py
T
Your Name 0b5f150691 Refactor and clean up code across multiple scripts
- Removed trailing whitespace and ensured files end with a single newline in cleanup_unused_files.py.
- Added fix_trailing_whitespace.py to batch remove trailing whitespace from Python files.
- Updated install_dependencies.py to improve dependency installation prompts.
- Cleaned up pick_coords.py by removing unnecessary whitespace and improving code readability.
- Enhanced region_selector.py by disabling specific pylint checks for better compatibility with third-party libraries.
- Improved WPS流程图生成工具.py by cleaning up whitespace and enhancing readability.
- Updated __init__.py in typings to remove unnecessary lines.
- Modified app.js to adjust default configuration values and clean up unused code.
2026-01-02 23:57:03 +08:00

197 lines
6.1 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试OCR识别速度
"""
import os
import sys
import time
from pathlib import Path
def test_ocr_speed(image_path: str, iterations: int = 5):
"""测试OCR识别速度"""
print("=" * 70)
print("OCR速度测试")
print("=" * 70)
print()
# 检查图片文件是否存在
if not os.path.exists(image_path):
print(f"[ERROR] 图片文件不存在: {image_path}")
return
file_size = os.path.getsize(image_path) / 1024 # KB
print(f"测试图片: {image_path}")
print(f"文件大小: {file_size:.2f} KB")
print(f"测试次数: {iterations} 次")
print()
# 获取图片信息
try:
from PIL import Image
img = Image.open(image_path)
width, height = img.size
print(f"图片尺寸: {width}x{height}")
print(f"图片模式: {img.mode}")
# 计算图片像素数
total_pixels = width * height
print(f"总像素数: {total_pixels:,}")
# 判断图片大小
if total_pixels > 2000000: # 大于200万像素
print(f" [提示] 图片较大,OCR处理可能需要较长时间")
print(f" 建议: 先裁剪到目标区域(如200x200)再OCR,可以显著提升速度")
print()
except Exception as e:
print(f"[WARNING] 无法读取图片信息: {e}")
print()
# 检查OCR引擎
print("1. OCR引擎信息")
print("-" * 70)
try:
from operations.ocr_operations import _ocr_processor
_ocr_processor._ensure_ocr()
if _ocr_processor.ocr is None:
print("[ERROR] OCR引擎未初始化")
return
print(f" OCR引擎: {_ocr_processor.ocr_type}")
print(f" OMP线程数: {os.environ.get('OMP_NUM_THREADS', '未设置')}")
print()
except Exception as e:
print(f"[ERROR] OCR引擎检查失败: {e}")
return
# 测试OCR速度
print("2. OCR速度测试")
print("-" * 70)
times = []
results = []
for i in range(iterations):
try:
# 导入OCR操作
from Underlying_Operations import underlying_operations
ops = underlying_operations()
# 确保OCR已初始化
ops._ensure_ocr()
# 执行OCR(使用analyse_pic_digits,因为这是数字识别)
start_time = time.time()
# 直接使用图片路径进行OCR
# 注意:如果图片很大,OCR会处理整个图片,这可能会很慢
# 建议使用预处理后的小图片进行测试
result = ops.analyse_pic_digits(
"测试图片",
change_color=1, # 数字识别模式
pic_path=image_path
)
# 记录各个阶段的耗时(如果可能)
# 注意:analyse_pic_digits 内部会进行图像预处理和OCR识别
elapsed = (time.time() - start_time) * 1000 # 转换为毫秒
times.append(elapsed)
results.append(result)
print(f" 第 {i+1} 次: {elapsed:.0f}ms, 识别结果: {result[:50] if result else '(空)'}")
except Exception as e:
print(f" 第 {i+1} 次: 失败 - {e}")
import traceback
traceback.print_exc()
print()
# 统计结果
if times:
print("3. 性能统计")
print("-" * 70)
avg_time = sum(times) / len(times)
min_time = min(times)
max_time = max(times)
print(f" 平均耗时: {avg_time:.0f}ms")
print(f" 最快耗时: {min_time:.0f}ms")
print(f" 最慢耗时: {max_time:.0f}ms")
print(f" 耗时范围: {max_time - min_time:.0f}ms")
print()
# 识别结果统计
print("4. 识别结果")
print("-" * 70)
unique_results = list(set(results))
for i, result in enumerate(unique_results, 1):
count = results.count(result)
print(f" 结果 {i}: {result[:100] if result else '(空)'} (出现 {count} 次)")
print()
# 性能评估
print("5. 性能评估")
print("-" * 70)
if avg_time < 500:
print(" [优秀] OCR速度很快 (< 500ms)")
elif avg_time < 1000:
print(" [良好] OCR速度良好 (500-1000ms)")
elif avg_time < 2000:
print(" [一般] OCR速度一般 (1000-2000ms)")
elif avg_time < 5000:
print(" [较慢] OCR速度较慢 (2000-5000ms)")
else:
print(" [很慢] OCR速度很慢 (> 5000ms)")
print(" 提示: 如果图片很大,建议先裁剪到目标区域再OCR")
# 多线程效果评估
cpu_count = os.cpu_count() or 4
omp_threads = int(os.environ.get('OMP_NUM_THREADS', '1'))
print(f" CPU核心数: {cpu_count}")
print(f" OMP线程数: {omp_threads}")
if omp_threads > 1:
print(f" [优化] 已启用底层多线程 (OMP_NUM_THREADS={omp_threads})")
else:
print(f" [提示] 未启用底层多线程,可以优化")
print()
else:
print("[ERROR] 所有测试都失败了")
print("=" * 70)
print("测试完成")
print("=" * 70)
def main():
"""主函数"""
# 默认图片路径
default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png"
# 从命令行参数获取图片路径
if len(sys.argv) > 1:
image_path = sys.argv[1]
else:
image_path = default_image
# 获取测试次数
iterations = 5
if len(sys.argv) > 2:
try:
iterations = int(sys.argv[2])
except:
pass
# 转换为绝对路径
if not os.path.isabs(image_path):
# 尝试相对于项目根目录
project_root = os.path.dirname(os.path.abspath(__file__))
image_path = os.path.join(project_root, image_path)
test_ocr_speed(image_path, iterations)
if __name__ == "__main__":
main()