ocr_utils.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import os
  2. os.environ["FLAGS_use_mkldnn"] = "0"
  3. os.environ["FLAGS_prim_skip_onednn"] = "1"
  4. os.environ["FLAGS_enable_pir_api"] = "0"
  5. import cv2
  6. import re
  7. from paddleocr import PaddleOCR
  8. # 初始化 PaddleOCR(只需初始化一次,可复用)
  9. ocr = PaddleOCR(use_angle_cls=True, lang='ch')
  10. def extract_text_from_image(image_path):
  11. """使用 PaddleOCR 从图片中提取文本"""
  12. try:
  13. # 使用 PaddleOCR 进行识别
  14. result = ocr.ocr(image_path)
  15. # 提取所有文本
  16. text_list = []
  17. if result and result[0]:
  18. for line in result[0]:
  19. text_list.append(line[1][0])
  20. # 合并所有识别的文本
  21. full_text = '\n'.join(text_list)
  22. return full_text.strip()
  23. except Exception as e:
  24. print(f"OCR 识别错误: {str(e)}")
  25. return ""
  26. def extract_id_card_info(image_path):
  27. """
  28. 从身份证图片中提取姓名和身份证号
  29. 返回: {'name': 姓名, 'id_number': 身份证号}
  30. """
  31. try:
  32. # 使用 PaddleOCR 识别身份证
  33. result = ocr.ocr(image_path)
  34. name = None
  35. id_number = None
  36. if result and result[0]:
  37. for line in result[0]:
  38. text = line[1][0]
  39. confidence = line[1][1]
  40. # 识别身份证号(18位或15位)
  41. id_match = re.search(r'\d{17}[\dxX]|\d{15}', text)
  42. if id_match and confidence > 0.8:
  43. id_number = id_match.group(0).upper()
  44. # 识别姓名(通常在"姓名"关键字后面)
  45. if '姓名' in text:
  46. # 获取姓名字段
  47. name_match = re.search(r'姓名[:\s]*([^\s]+)', text)
  48. if name_match:
  49. name = name_match.group(1)
  50. # 或者直接识别中文姓名(2-4个汉字)
  51. elif not name and confidence > 0.9:
  52. name_match = re.search(r'^[一-龥]{2,4}$', text)
  53. if name_match:
  54. name = name_match.group(0)
  55. return {
  56. 'name': name,
  57. 'id_number': id_number
  58. }
  59. except Exception as e:
  60. print(f"身份证识别错误: {str(e)}")
  61. return {
  62. 'name': None,
  63. 'id_number': None
  64. }
  65. # 示例调用
  66. if __name__ == "__main__":
  67. # 测试普通 OCR
  68. text = extract_text_from_image('path_to_image.png')
  69. print("提取的文本:", text)
  70. # 测试身份证识别
  71. id_info = extract_id_card_info('path_to_id_card.jpg')
  72. print("身份证信息:", id_info)