patches.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
  2. """Monkey patches to update/extend functionality of existing functions."""
  3. import time
  4. from pathlib import Path
  5. import cv2
  6. import numpy as np
  7. import torch
  8. # OpenCV Multilanguage-friendly functions ------------------------------------------------------------------------------
  9. _imshow = cv2.imshow # copy to avoid recursion errors
  10. def imread(filename: str, flags: int = cv2.IMREAD_COLOR):
  11. """
  12. Read an image from a file.
  13. Args:
  14. filename (str): Path to the file to read.
  15. flags (int, optional): Flag that can take values of cv2.IMREAD_*. Defaults to cv2.IMREAD_COLOR.
  16. Returns:
  17. (np.ndarray): The read image.
  18. """
  19. return cv2.imdecode(np.fromfile(filename, np.uint8), flags)
  20. def imwrite(filename: str, img: np.ndarray, params=None):
  21. """
  22. Write an image to a file.
  23. Args:
  24. filename (str): Path to the file to write.
  25. img (np.ndarray): Image to write.
  26. params (list of ints, optional): Additional parameters. See OpenCV documentation.
  27. Returns:
  28. (bool): True if the file was written, False otherwise.
  29. """
  30. try:
  31. cv2.imencode(Path(filename).suffix, img, params)[1].tofile(filename)
  32. return True
  33. except Exception:
  34. return False
  35. def imshow(winname: str, mat: np.ndarray):
  36. """
  37. Displays an image in the specified window.
  38. Args:
  39. winname (str): Name of the window.
  40. mat (np.ndarray): Image to be shown.
  41. """
  42. _imshow(winname.encode("unicode_escape").decode(), mat)
  43. # PyTorch functions ----------------------------------------------------------------------------------------------------
  44. _torch_load = torch.load # copy to avoid recursion errors
  45. _torch_save = torch.save
  46. def torch_load(*args, **kwargs):
  47. """
  48. Load a PyTorch model with updated arguments to avoid warnings.
  49. This function wraps torch.load and adds the 'weights_only' argument for PyTorch 1.13.0+ to prevent warnings.
  50. Args:
  51. *args (Any): Variable length argument list to pass to torch.load.
  52. **kwargs (Any): Arbitrary keyword arguments to pass to torch.load.
  53. Returns:
  54. (Any): The loaded PyTorch object.
  55. Note:
  56. For PyTorch versions 2.0 and above, this function automatically sets 'weights_only=False'
  57. if the argument is not provided, to avoid deprecation warnings.
  58. """
  59. from ultralytics.utils.torch_utils import TORCH_1_13
  60. if TORCH_1_13 and "weights_only" not in kwargs:
  61. kwargs["weights_only"] = False
  62. return _torch_load(*args, **kwargs)
  63. def torch_save(*args, **kwargs):
  64. """
  65. Optionally use dill to serialize lambda functions where pickle does not, adding robustness with 3 retries and
  66. exponential standoff in case of save failure.
  67. Args:
  68. *args (tuple): Positional arguments to pass to torch.save.
  69. **kwargs (Any): Keyword arguments to pass to torch.save.
  70. """
  71. for i in range(4): # 3 retries
  72. try:
  73. return _torch_save(*args, **kwargs)
  74. except RuntimeError as e: # unable to save, possibly waiting for device to flush or antivirus scan
  75. if i == 3:
  76. raise e
  77. time.sleep((2**i) / 2) # exponential standoff: 0.5s, 1.0s, 2.0s