orcUtils.py 977 B

1234567891011121314151617181920212223242526272829
  1. import logging
  2. import pytesseract
  3. from PIL import Image
  4. # 配置日志记录
  5. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  6. # 如果 Tesseract-OCR 不在 PATH 中,需要指定其路径
  7. pytesseract.pytesseract.tesseract_cmd = r'G:\资料\tools\tesseract-ocr-master\Tesseract-OCR\tesseract.exe'
  8. # 打开图片文件
  9. image = Image.open('G:\\1111.jpg')
  10. try:
  11. # 使用 pytesseract 进行 OCR 识别,并指定编码
  12. text = pytesseract.image_to_string(image, lang='chi_sim') # 如果图片是中文,可以指定语言
  13. logging.info("OCR识别成功")
  14. except Exception as e:
  15. logging.error(f"OCR识别失败: {e}")
  16. text = ""
  17. # 打印识别的文字
  18. try:
  19. print(text.encode('utf-8', errors='ignore').decode('utf-8'))
  20. except UnicodeDecodeError as e:
  21. print(f"UnicodeDecodeError: {e}")
  22. print("尝试使用 'replace' 处理编码错误")
  23. print(text.encode('utf-8', errors='replace').decode('utf-8'))