cv.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 typing import Optional, Tuple
  16. import cv2
  17. import numpy as np
  18. from numpy.typing import ArrayLike
  19. from ... import utils as serving_utils
  20. from ...storage import Storage, SupportsGetURL
  21. def postprocess_image(
  22. image: ArrayLike,
  23. log_id: str,
  24. filename: str,
  25. *,
  26. file_storage: Optional[Storage] = None,
  27. return_url: bool = False,
  28. max_img_size: Optional[Tuple[int, int]] = None,
  29. ) -> str:
  30. if return_url:
  31. if not file_storage:
  32. raise ValueError(
  33. "`file_storage` must not be None when URLs need to be returned."
  34. )
  35. if not isinstance(file_storage, SupportsGetURL):
  36. raise TypeError("The provided storage does not support getting URLs.")
  37. key = f"{log_id}/{filename}"
  38. ext = os.path.splitext(filename)[1]
  39. image = np.asarray(image)
  40. h, w = image.shape[0:2]
  41. if w > max_img_size[1] or h > max_img_size[0]:
  42. if w / h > max_img_size[0] / max_img_size[1]:
  43. factor = max_img_size[0] / w
  44. else:
  45. factor = max_img_size[1] / h
  46. image = cv2.resize(image, (int(factor * w), int(factor * h)))
  47. img_bytes = serving_utils.image_array_to_bytes(image, ext=ext)
  48. if file_storage is not None:
  49. file_storage.set(key, img_bytes)
  50. if return_url:
  51. assert isinstance(file_storage, SupportsGetURL)
  52. return file_storage.get_url(key)
  53. return serving_utils.base64_encode(img_bytes)