paddle_table_cls.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import os
  2. import cv2
  3. import numpy as np
  4. import onnxruntime
  5. from loguru import logger
  6. from mineru.backend.pipeline.model_list import AtomicModel
  7. from mineru.utils.enum_class import ModelPath
  8. from mineru.utils.models_download_utils import auto_download_and_get_model_root_path
  9. class PaddleTableClsModel:
  10. def __init__(self):
  11. self.sess = onnxruntime.InferenceSession(
  12. os.path.join(auto_download_and_get_model_root_path(ModelPath.paddle_table_cls), ModelPath.paddle_table_cls)
  13. )
  14. self.less_length = 256
  15. self.cw, self.ch = 224, 224
  16. self.std = [0.229, 0.224, 0.225]
  17. self.scale = 0.00392156862745098
  18. self.mean = [0.485, 0.456, 0.406]
  19. self.labels = [AtomicModel.WiredTable, AtomicModel.WirelessTable]
  20. def preprocess(self, img):
  21. # PIL图像转cv2
  22. img = np.array(img)
  23. # 放大图片,使其最短边长为256
  24. h, w = img.shape[:2]
  25. scale = 256 / min(h, w)
  26. h_resize = round(h * scale)
  27. w_resize = round(w * scale)
  28. img = cv2.resize(img, (w_resize, h_resize), interpolation=1)
  29. # 调整为224*224的正方形
  30. h, w = img.shape[:2]
  31. cw, ch = 224, 224
  32. x1 = max(0, (w - cw) // 2)
  33. y1 = max(0, (h - ch) // 2)
  34. x2 = min(w, x1 + cw)
  35. y2 = min(h, y1 + ch)
  36. if w < cw or h < ch:
  37. raise ValueError(
  38. f"Input image ({w}, {h}) smaller than the target size ({cw}, {ch})."
  39. )
  40. img = img[y1:y2, x1:x2, ...]
  41. # 正则化
  42. split_im = list(cv2.split(img))
  43. std = [0.229, 0.224, 0.225]
  44. scale = 0.00392156862745098
  45. mean = [0.485, 0.456, 0.406]
  46. alpha = [scale / std[i] for i in range(len(std))]
  47. beta = [-mean[i] / std[i] for i in range(len(std))]
  48. for c in range(img.shape[2]):
  49. split_im[c] = split_im[c].astype(np.float32)
  50. split_im[c] *= alpha[c]
  51. split_im[c] += beta[c]
  52. img = cv2.merge(split_im)
  53. # 5. 转换为 CHW 格式
  54. img = img.transpose((2, 0, 1))
  55. imgs = [img]
  56. x = np.stack(imgs, axis=0).astype(dtype=np.float32, copy=False)
  57. return x
  58. def predict(self, img):
  59. x = self.preprocess(img)
  60. result = self.sess.run(None, {"x": x})
  61. idx = np.argmax(result)
  62. conf = float(np.max(result))
  63. # logger.debug(f"Table classification result: {self.labels[idx]} with confidence {conf:.4f}")
  64. if idx == 0 and conf < 0.8:
  65. idx = 1
  66. return self.labels[idx], conf