image_reader.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  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. from ....utils.deps import class_requires_deps, is_dep_available
  16. from ...utils.benchmark import benchmark
  17. from ...utils.io import ImageReader
  18. if is_dep_available("opencv-contrib-python"):
  19. import cv2
  20. @benchmark.timeit_with_options(name=None, is_read_operation=True)
  21. @class_requires_deps("opencv-contrib-python")
  22. class ReadImage:
  23. """Load image from the file."""
  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 = {
  34. "BGR": cv2.IMREAD_COLOR,
  35. "RGB": cv2.IMREAD_COLOR,
  36. "GRAY": cv2.IMREAD_GRAYSCALE,
  37. }[self.format]
  38. self._img_reader = ImageReader(backend="opencv", flags=flags)
  39. def __call__(self, imgs):
  40. """apply"""
  41. return [self.read(img) for img in imgs]
  42. def read(self, img):
  43. if isinstance(img, np.ndarray):
  44. if self.format == "RGB":
  45. img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  46. return img
  47. elif isinstance(img, str):
  48. blob = self._img_reader.read(img)
  49. if blob is None:
  50. raise Exception(f"Image read Error: {img}")
  51. if self.format == "RGB":
  52. if blob.ndim != 3:
  53. raise RuntimeError("Array is not 3-dimensional.")
  54. # BGR to RGB
  55. blob = cv2.cvtColor(blob, cv2.COLOR_BGR2RGB)
  56. return blob
  57. else:
  58. raise TypeError(
  59. f"ReadImage only supports the following types:\n"
  60. f"1. str, indicating a image file path or a directory containing image files.\n"
  61. f"2. numpy.ndarray.\n"
  62. f"However, got type: {type(img).__name__}."
  63. )