单例模式
在你提供的代码中,reader
被定义为全局变量。要在其他地方使用这个 reader
对象,你可以通过以下几种方式实现:
1. 直接引用全局变量
如果你在同一个模块的其他函数或者方法中使用 reader
,可以直接引用这个全局变量。不过需要注意,在使用之前要确保 ready
方法已经被调用并成功创建了 reader
对象。
import os
import sys
import time
import subprocess
from django.apps import AppConfig
from django.core.cache import cache
import easyocr
# 全局变量
reader = None
class ApiConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "api"
def ready(self):
# 确保只运行一次
if os.environ.get('RUN_MAIN') == 'true':
# 创建reader
print(f"--------------------------创建reader----------------------------------")
start = time.time()
global reader
reader = easyocr.Reader(['ch_sim', 'en'],
gpu=True, # 强制使用GPU
quantize=True, # 量化模型减小体积
model_storage_directory='./model_cache') # 缓存模型
print(f"--------------------------reader创建完成,用时:{time.time() - start}----------------------------------")
# 创建客户端
venv_python = os.path.join(os.path.dirname(sys.executable), 'python')
subprocess.Popen([venv_python, 'scripts/pyqt_client.py'])
# 同一模块的其他函数中使用 reader
def perform_ocr(image_path):
global reader
if reader:
result = reader.readtext(image_path)
return result
else:
print("Reader 还未创建,请等待。")
return []
2. 在不同模块中使用
如果你需要在不同的模块中使用 reader
,可以将 reader
封装在一个单例类中,或者通过配置文件、上下文管理器等方式进行传递。
使用单例类封装 reader
# singleton_reader.py
import easyocr
class SingletonReader:
_instance = None
_reader = None
def __new__(cls):
if not cls._instance:
cls._instance = super().__new__(cls)
cls._reader = easyocr.Reader(['ch_sim', 'en'],
gpu=True,
quantize=True,
model_storage_directory='./model_cache')
return cls._instance
@classmethod
def get_reader(cls):
return cls._reader
# 在 ApiConfig 中使用单例类
from django.apps import AppConfig
import subprocess
import os
import sys
from singleton_reader import SingletonReader
class ApiConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "api"
def ready(self):
if os.environ.get('RUN_MAIN') == 'true':
# 获取 reader
reader = SingletonReader.get_reader()
# 创建客户端
venv_python = os.path.join(os.path.dirname(sys.executable), 'python')
subprocess.Popen([venv_python, 'scripts/pyqt_client.py'])
# 在其他模块中使用单例类
from singleton_reader import SingletonReader
def perform_ocr(image_path):
reader = SingletonReader.get_reader()
result = reader.readtext(image_path)
return result
通过以上方法,你可以在不同的地方方便地使用创建好的 reader
对象进行 OCR 识别。