Files
douyin_guaji-main/test_ocr_speed_optimized.py
T
Your Name 07c387751d chore: Clean up blank lines across multiple files to enhance readability
- Removed excessive blank lines in various Python scripts, markdown files, and configuration files to improve overall code clarity and maintainability.
- Ensured consistent formatting throughout the project, contributing to a more organized codebase.
2025-12-31 17:00:58 +08:00

215 lines
6.7 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试OCR识别速度(优化版 - 支持裁剪区域测试)
"""
import os
import sys
import time
from typing import Optional
from PIL import Image
def test_ocr_on_region(image_path: str, region: Optional[tuple] = None, iterations: int = 5):
"""在指定区域测试OCR速度"""
print("=" * 70)
print("OCR速度测试(区域优化版)")
print("=" * 70)
print()
# 检查图片文件是否存在
if not os.path.exists(image_path):
print(f"[ERROR] 图片文件不存在: {image_path}")
return
# 加载图片
try:
img = Image.open(image_path)
original_size = img.size
print(f"原始图片: {image_path}")
print(f"原始尺寸: {original_size[0]}x{original_size[1]}")
print(f"原始像素数: {original_size[0] * original_size[1]:,}")
print()
except Exception as e:
print(f"[ERROR] 无法加载图片: {e}")
return
# 如果指定了区域,裁剪图片
if region:
x1, y1, x2, y2 = region
img = img.crop((x1, y1, x2, y2))
print(f"裁剪区域: ({x1}, {y1}) - ({x2}, {y2})")
print(f"裁剪后尺寸: {img.size[0]}x{img.size[1]}")
print(f"裁剪后像素数: {img.size[0] * img.size[1]:,}")
print()
# 保存裁剪后的临时图片
import tempfile
temp_dir = tempfile.gettempdir()
temp_image = os.path.join(temp_dir, "ocr_test_crop.png")
img.save(temp_image)
test_image_path = temp_image
else:
test_image_path = image_path
# 测试OCR速度
print("开始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
# 执行多次测试
times = []
results = []
for i in range(iterations):
try:
import numpy as np
# 准备图像
if img.mode != 'RGB':
img_rgb = img.convert('RGB')
else:
img_rgb = img
# 转换为numpy数组
img_np = np.array(img_rgb)
# 执行OCR
start_time = time.time()
if _ocr_processor.ocr_type == "easyocr":
result = _ocr_processor.ocr.readtext(img_np)
else:
result = _ocr_processor.ocr.ocr(img_np)
elapsed = (time.time() - start_time) * 1000 # 转换为毫秒
# 提取文本
from Underlying_Operations import underlying_operations
ops = underlying_operations()
text = ops.extract_ocr_content(result)
times.append(elapsed)
results.append(text)
print(f"第 {i+1} 次: {elapsed:.0f}ms, 识别结果: {text[:50] if text else '(空)'}")
except Exception as e:
print(f"第 {i+1} 次: 失败 - {e}")
import traceback
traceback.print_exc()
print()
# 统计结果
if times:
print("性能统计")
print("-" * 70)
avg_time = sum(times) / len(times)
min_time = min(times)
max_time = max(times)
print(f"平均耗时: {avg_time:.0f}ms ({avg_time/1000:.2f}秒)")
print(f"最快耗时: {min_time:.0f}ms ({min_time/1000:.2f}秒)")
print(f"最慢耗时: {max_time:.0f}ms ({max_time/1000:.2f}秒)")
print(f"耗时范围: {max_time - min_time:.0f}ms")
print()
# 识别结果
print("识别结果")
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()
# 性能对比
if region:
original_pixels = original_size[0] * original_size[1]
crop_pixels = img.size[0] * img.size[1]
reduction = (1 - crop_pixels / original_pixels) * 100
print("性能对比")
print("-" * 70)
print(f"原始图片像素: {original_pixels:,}")
print(f"裁剪后像素: {crop_pixels:,}")
print(f"像素减少: {reduction:.1f}%")
print(f"预计原始图片OCR耗时: {avg_time * (original_pixels / crop_pixels):.0f}ms")
print()
# 清理临时文件
if region and os.path.exists(test_image_path):
try:
os.remove(test_image_path)
except:
pass
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
# 转换为绝对路径
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)
# 从文件名提取区域信息(如果文件名包含坐标)
region = None
if "(480,1110)-(570,1230)" in image_path:
# 提取坐标
region = (480, 1110, 570, 1230)
print("[INFO] 检测到文件名中的坐标信息,将使用裁剪区域进行测试")
print()
# 获取测试次数
iterations = 5
if len(sys.argv) > 2:
try:
iterations = int(sys.argv[2])
except:
pass
# 先测试完整图片
print("=" * 70)
print("测试1: 完整图片OCR")
print("=" * 70)
test_ocr_on_region(image_path, region=None, iterations=iterations)
# 如果检测到区域信息,再测试裁剪区域
if region:
print()
print("=" * 70)
print("测试2: 裁剪区域OCR(推荐)")
print("=" * 70)
test_ocr_on_region(image_path, region=region, iterations=iterations)
if __name__ == "__main__":
main()