patches.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. # Ultralytics YOLO 🚀, AGPL-3.0 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_save = torch.save # copy to avoid recursion errors
  45. def torch_save(*args, use_dill=True, **kwargs):
  46. """
  47. Optionally use dill to serialize lambda functions where pickle does not, adding robustness with 3 retries and
  48. exponential standoff in case of save failure.
  49. Args:
  50. *args (tuple): Positional arguments to pass to torch.save.
  51. use_dill (bool): Whether to try using dill for serialization if available. Defaults to True.
  52. **kwargs (any): Keyword arguments to pass to torch.save.
  53. """
  54. try:
  55. assert use_dill
  56. import dill as pickle
  57. except (AssertionError, ImportError):
  58. import pickle
  59. if "pickle_module" not in kwargs:
  60. kwargs["pickle_module"] = pickle
  61. for i in range(4): # 3 retries
  62. try:
  63. return _torch_save(*args, **kwargs)
  64. except RuntimeError as e: # unable to save, possibly waiting for device to flush or antivirus scan
  65. if i == 3:
  66. raise e
  67. time.sleep((2**i) / 2) # exponential standoff: 0.5s, 1.0s, 2.0s