image_reader.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 numpy as np
  15. import cv2
  16. from ...utils.io import ImageReader, PDFReader
  17. class ReadImage:
  18. """Load image from the file."""
  19. _FLAGS_DICT = {
  20. "BGR": cv2.IMREAD_COLOR,
  21. "RGB": cv2.IMREAD_COLOR,
  22. "GRAY": cv2.IMREAD_GRAYSCALE,
  23. }
  24. def __init__(self, format="BGR"):
  25. """
  26. Initialize the instance.
  27. Args:
  28. format (str, optional): Target color format to convert the image to.
  29. Choices are 'BGR', 'RGB', and 'GRAY'. Default: 'BGR'.
  30. """
  31. super().__init__()
  32. self.format = format
  33. flags = self._FLAGS_DICT[self.format]
  34. self._img_reader = ImageReader(backend="opencv", flags=flags)
  35. def __call__(self, imgs):
  36. """apply"""
  37. return [self.read(img) for img in imgs]
  38. def read(self, img):
  39. if isinstance(img, np.ndarray):
  40. if self.format == "RGB":
  41. img = img[:, :, ::-1]
  42. return img
  43. elif isinstance(img, str):
  44. blob = self._img_reader.read(img)
  45. if blob is None:
  46. raise Exception(f"Image read Error: {img}")
  47. if self.format == "RGB":
  48. if blob.ndim != 3:
  49. raise RuntimeError("Array is not 3-dimensional.")
  50. # BGR to RGB
  51. blob = blob[..., ::-1]
  52. return blob
  53. else:
  54. raise TypeError(
  55. f"ReadImage only supports the following types:\n"
  56. f"1. str, indicating a image file path or a directory containing image files.\n"
  57. f"2. numpy.ndarray.\n"
  58. f"However, got type: {type(img).__name__}."
  59. )