transforms.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. from pathlib import Path
  16. import numpy as np
  17. from .keys import WarpKeys as K
  18. from ...base import BaseTransform
  19. from ...base.predictor.io import ImageWriter, ImageReader
  20. from ....utils import logging
  21. _all__ = ['DocTrPostProcess', 'SaveDocTrResults']
  22. class DocTrPostProcess(BaseTransform):
  23. """ normalize image such as substract mean, divide std
  24. """
  25. def __init__(self, scale=None, **kwargs):
  26. if isinstance(scale, str):
  27. scale = eval(scale)
  28. self.scale = np.float32(scale if scale is not None else 255.0)
  29. def apply(self, data):
  30. im = data[K.DOCTR_IMG]
  31. assert isinstance(im,
  32. np.ndarray), "invalid input 'im' in DocTrPostProcess"
  33. im = im.squeeze()
  34. im = im.transpose(1, 2, 0)
  35. im *= self.scale
  36. im = im[:, :, ::-1]
  37. im = im.astype("uint8", copy=False)
  38. data[K.DOCTR_IMG] = im
  39. return data
  40. @classmethod
  41. def get_input_keys(cls):
  42. return [K.DOCTR_IMG]
  43. @classmethod
  44. def get_output_keys(cls):
  45. return [K.DOCTR_IMG]
  46. class SaveDocTrResults(BaseTransform):
  47. _FILE_EXT = '.png'
  48. def __init__(self, save_dir, file_name=None):
  49. super().__init__()
  50. self.save_dir = save_dir
  51. self._writer = ImageWriter(backend='opencv')
  52. @staticmethod
  53. def _replace_ext(path, new_ext):
  54. """replace ext"""
  55. stem, _ = os.path.splitext(path)
  56. return stem + new_ext
  57. def apply(self, data):
  58. ori_path = data[K.IM_PATH]
  59. file_name = os.path.basename(ori_path)
  60. file_name = self._replace_ext(file_name, self._FILE_EXT)
  61. save_path = os.path.join(self.save_dir, file_name)
  62. doctr_img = data[K.DOCTR_IMG]
  63. self._writer.write(save_path, doctr_img)
  64. return data
  65. @classmethod
  66. def get_input_keys(cls):
  67. return [K.DOCTR_IMG]
  68. @classmethod
  69. def get_output_keys(cls):
  70. return []