|
@@ -1,16 +1,34 @@
|
|
|
-from paddleocr import PaddleOCR
|
|
|
-from PIL import Image, ImageGrab
|
|
|
-import numpy as np
|
|
|
+import importlib
|
|
|
|
|
|
-# 定义截图和OCR识别函数
|
|
|
def capture_and_ocr(region):
|
|
|
- # 读取屏幕截图
|
|
|
- screenshot = ImageGrab.grab(bbox=region)
|
|
|
- # 将 PIL.Image 转换为 numpy 数组
|
|
|
- screenshot_np = np.array(screenshot)
|
|
|
+ # 动态导入所需库
|
|
|
+ Image = importlib.import_module('PIL.Image')
|
|
|
+ ImageGrab = importlib.import_module('PIL.ImageGrab')
|
|
|
+ np = importlib.import_module('numpy')
|
|
|
+ PaddleOCR = importlib.import_module('paddleocr').PaddleOCR
|
|
|
|
|
|
- ocr = PaddleOCR(use_angle_cls=True) # 支持中文
|
|
|
- result = ocr.ocr(screenshot_np, cls=True)
|
|
|
- final_texts = [line[1][0] for line in result[0]] # 提取每个识别结果的文本部分
|
|
|
- return final_texts
|
|
|
-
|
|
|
+ try:
|
|
|
+ # 读取屏幕截图
|
|
|
+ screenshot = ImageGrab.grab(bbox=region)
|
|
|
+ # 将 PIL.Image 转换为 numpy 数组
|
|
|
+ screenshot_np = np.array(screenshot)
|
|
|
+
|
|
|
+ # 初始化OCR(只在需要时创建)
|
|
|
+ ocr = PaddleOCR(use_angle_cls=True) # 支持中文
|
|
|
+ result = ocr.ocr(screenshot_np, cls=True)
|
|
|
+
|
|
|
+ # 提取每个识别结果的文本部分
|
|
|
+ final_texts = [line[1][0] for line in result[0]]
|
|
|
+ return final_texts
|
|
|
+
|
|
|
+ finally:
|
|
|
+ # 清理内存
|
|
|
+ del Image, ImageGrab, np, PaddleOCR, ocr, screenshot, screenshot_np
|
|
|
+ if 'result' in locals():
|
|
|
+ del result
|
|
|
+ if 'final_texts' in locals():
|
|
|
+ del final_texts
|
|
|
+
|
|
|
+ # 强制垃圾回收
|
|
|
+ import gc
|
|
|
+ gc.collect()
|