123456789101112131415161718192021222324252627282930313233343536 |
- import importlib
- def capture_and_ocr(region):
- # 动态导入所需库
- Image = importlib.import_module('PIL.Image')
- ImageGrab = importlib.import_module('PIL.ImageGrab')
- np = importlib.import_module('numpy')
- PaddleOCR = importlib.import_module('paddleocr').PaddleOCR
- 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()
- return ""
|