file_picture.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. # -*-coding:utf-8 -*-
  2. """
  3. 任务发布者
  4. """
  5. import cv2 as cv
  6. import grpc
  7. from util.picture_zooming import PictureZooming
  8. from servicerd.client import RdClient
  9. from proto import ocr_pb2_grpc
  10. from proto import ocr_pb2
  11. from docs.config import picture_config
  12. from loguru import logger
  13. from file_processing.tr_ocr import tr_ocr_patch
  14. from docs.config import error_number
  15. zoom = PictureZooming()
  16. cd = RdClient(service_name=picture_config["service_name"],
  17. rd_server=picture_config["rd_server"],
  18. balance_type=picture_config["balance_type"])
  19. def run(param, **kwargs) -> (bool, any):
  20. address = '{}:{}'.format(kwargs['ip'], kwargs['port'])
  21. print(address)
  22. with grpc.insecure_channel(address) as channel:
  23. stub = ocr_pb2_grpc.OcrStub(channel)
  24. response = stub.Ocr(ocr_pb2.OcrRequest(image=param[1]))
  25. # print("Greeter client received: " + response.message)
  26. return param[0], response.message
  27. def execute_ocr(image_list):
  28. try:
  29. image_text = {}
  30. images = []
  31. # 图片缩放
  32. for position, image_path in image_list:
  33. img_file = read_image(image_path)
  34. if (not img_file) or isinstance(img_file, str):
  35. continue
  36. images.append((position, img_file))
  37. if images:
  38. # 批量识别
  39. ocr_results = cd.parallel_computing(images, 20, run)
  40. for values in ocr_results:
  41. if len(values) < 2:
  42. continue
  43. if values[1]:
  44. image_text[values[0]] = values[1]
  45. return image_text
  46. except Exception as e:
  47. logger.warning(f"ocr is fail->{e}"), error_number["解析错误"]
  48. return {}
  49. def read_image(filepath):
  50. try:
  51. load_image = cv.imread(filepath)
  52. x, y, z = load_image.shape
  53. # 图片大小判断
  54. if y < 600 or x < 500:
  55. return ""
  56. # 图片缩放
  57. load_image = zoom.patch(load_image)
  58. # 格式转换
  59. load_image = cv.imencode(".jpg", load_image)[1].tobytes()
  60. return load_image
  61. except Exception as e:
  62. return {}
  63. OcrType = "common"
  64. ocr_select = {"tr": tr_ocr_patch, "common": execute_ocr}
  65. def ocr(images_path):
  66. global OcrType
  67. if not images_path:
  68. return {}, error_number["解析错误"]
  69. images = [(0, images_path)]
  70. result = ocr_select[OcrType](images)
  71. return result.get(0, ""), error_number["成功"]
  72. def ocr_patch(images):
  73. '''
  74. :param images:
  75. :param ocr_type:
  76. :return:
  77. '''
  78. global OcrType
  79. if not images:
  80. return {}
  81. result = ocr_select[OcrType](images)
  82. return result