【PYTHON】使用easyocr作为服务进行图片中的文字识别

📅 发布时间:2026/8/23 23:36:09
【PYTHON】使用easyocr作为服务进行图片中的文字识别
【PYTHON】使用easyocr作为服务进行图片中的文字识别场景EASYOCR服务端客户端场景普通的WINDOWS电脑上有310和39x的python环境主程序使用310python由于电脑限制当前310python安装不了easyocr加上easyocr加载模型时间比较长。所以把easyocr在39x环境下当做一个服务来调用。EASYOCR服务端pip install fastapi uvicorn easyocr mss pillow numpyocr_server.pyimportdatetimeimportjsonfromfastapiimportFastAPIfrompydanticimportBaseModelimportctypesimportmssfromPILimportImageimportnumpyasnpimporteasyocr# 全局初始化服务启动仅执行1次# 解决Windows高DPI多屏坐标偏移try:ctypes.windll.shcore.SetProcessDpiAwareness(2)exceptException:passappFastAPI(title屏幕OCR服务)print(f[{datetime.datetime.now().strftime(%Y-%m-%d %H:%M:%S)}] 正在初始化 EasyOCR 模型...)# 全局reader只加载一次不随接口调用重复加载readereasyocr.Reader([ch_sim,en],gpuFalse)print(f[{datetime.datetime.now().strftime(%Y-%m-%d %H:%M:%S)}] ✅ OCR模型初始化完成可以接收请求)defget_time_str():returndatetime.datetime.now().strftime(%Y-%m-%d %H:%M:%S)defocr_screen_region(bbox): bbox: (left, top, right, bottom) try:left,top,right,bottombboxwithmss.mss()assct:monitor{left:left,top:top,width:right-left,height:bottom-top}sct_imgsct.grab(monitor)pil_imgImage.frombytes(RGB,sct_img.size,sct_img.rgb)img_arraynp.array(pil_img)detectionsreader.readtext(img_array,text_threshold0.7,low_text0.3,link_threshold0.3,mag_ratio1.6)extracted_text[]fordetectionindetections:bbox_coords,text,confidencedetection extracted_text.append({text:text,confidence:round(confidence,2)})print(f[{get_time_str()}] [置信度:{confidence:.2f}] -{text})return{success:True,data:extracted_text}exceptExceptionase:print(f[{get_time_str()}] ❌ OCR识别异常:{str(e)})return{success:False,error:str(e)}# GET接口把坐标作为url查询参数传入 app.get(/ocr)defapi_ocr(left:int,top:int,right:int,bottom:int): http://127.0.0.1:8000/ocr?left4290top243right5497bottom896 bbox(left,top,right,bottom)resultocr_screen_region(bbox)returnresultif__name____main__:importuvicorn uvicorn.run(app,host127.0.0.1,port8000)启动服务C:\Users\3333\AppData\Local\Programs\Python\Python39\python.exe .\ocr_server.py客户端importrequestsdefrun_py39_script():left,top,right,bottom4290,243,5497,896urlfhttp://127.0.0.1:8000/ocr?left{left}top{top}right{right}bottom{bottom}try:resprequests.get(url,timeout15)resp.raise_for_status()result_jsonresp.json()stdoutresp.text stderrreturncode0exceptrequests.exceptions.RequestExceptionase:result_jsonNonestdoutstderrstr(e)returncode-1print(接口返回原始stdout)print(stdout)ifstderr:print(调用错误stderr)print(stderr)print(f调用退出码:{returncode})returnresult_json,stdout,stderr,returncodeif__name____main__:res,out,err,coderun_py39_script()ifresandres[success]:print(识别文本列表,res[data])forxinres[data]:print(x)