-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathutils.py
More file actions
310 lines (238 loc) · 8.62 KB
/
utils.py
File metadata and controls
310 lines (238 loc) · 8.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
"""
DeepLabCut Toolbox (deeplabcut.org)
© A. & M. Mathis Labs
Licensed under GNU Lesser General Public License v3.0
"""
import urllib.error
import urllib.request
import warnings
from pathlib import Path
import cv2
import numpy as np
from tqdm import tqdm
from dlclive.engine import Engine
from dlclive.exceptions import DLCLiveWarning
def get_torch(required: bool = False, feature: str | None = None):
"""Lazily import torch.
Args:
required: If True, raise a clear error when torch is unavailable.
feature: Optional feature name to include in error messages.
Returns:
The imported torch module, or None when unavailable and not required.
"""
try:
import torch
return torch
except (ImportError, ModuleNotFoundError) as exc:
if required:
context = f" for {feature}" if feature else ""
raise ModuleNotFoundError(
f"PyTorch is required{context} but is not installed. "
"Install it with: pip install deeplabcut-live[pytorch]"
) from exc
return None
def get_tensorflow(required: bool = False, feature: str | None = None):
"""Lazily import tensorflow.
Args:
required: If True, raise a clear error when tensorflow is unavailable.
feature: Optional feature name to include in error messages.
Returns:
The imported tensorflow module, or None when unavailable and not required.
"""
try:
import tensorflow as tf
return tf
except (ImportError, ModuleNotFoundError) as exc:
if required:
context = f" for {feature}" if feature else ""
raise ModuleNotFoundError(
f"TensorFlow is required{context} but is not installed. "
"Install it with: pip install deeplabcut-live[tf]"
) from exc
return None
def convert_to_ubyte(frame: np.ndarray) -> np.ndarray:
"""Converts an image to unsigned 8-bit integer numpy array.
If scikit-image is installed, uses skimage.img_as_ubyte, otherwise, uses a similar custom function.
Parameters
----------
frame:
an image as a numpy array
Returns
-------
:class: `numpy.ndarray`
image converted to uint8
"""
return _img_as_ubyte_np(frame)
def resize_frame(frame: np.ndarray, resize=None) -> np.ndarray:
"""Resizes an image using OpenCV.
Parameters
----------
frame:
an image as a numpy array
"""
if (resize is not None) and (resize != 1):
new_x = int(frame.shape[0] * resize)
new_y = int(frame.shape[1] * resize)
return cv2.resize(frame, (new_y, new_x))
else:
return frame
def img_to_rgb(frame: np.ndarray) -> np.ndarray:
"""Convert an image to RGB using OpenCV.
Parameters
----------
frame : :class:`numpy.ndarray
an image as a numpy array
"""
if frame.ndim == 2:
return gray_to_rgb(frame)
elif frame.ndim == 3:
return bgr_to_rgb(frame)
else:
warnings.warn(
f"Image has {frame.ndim} dimensions. Must be 2 or 3 dimensions to convert to RGB",
DLCLiveWarning,
stacklevel=2,
)
return frame
def gray_to_rgb(frame: np.ndarray) -> np.ndarray:
"""Convert an image from grayscale to RGB using OpenCV.
Parameters
----------
frame : :class:`numpy.ndarray
an image as a numpy array
"""
return cv2.cvtColor(frame, cv2.COLOR_GRAY2RGB)
def bgr_to_rgb(frame: np.ndarray) -> np.ndarray:
"""Convert an image from BGR to RGB using OpenCV.
Parameters
----------
frame : :class:`numpy.ndarray
an image as a numpy array
"""
return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
def _img_as_ubyte_np(frame: np.ndarray) -> np.ndarray:
"""Converts an image as a numpy array to unsinged 8-bit integer.
As in scikit-image img_as_ubyte, converts negative pixels to 0 and converts range to [0, 255]
Parameters
----------
image : :class:`numpy.ndarray`
an image as a numpy array
Returns
-------
:class:`numpy.ndarray`
image converted to uint8
"""
frame = np.array(frame)
im_type = frame.dtype.type
# check if already ubyte
if np.issubdtype(im_type, np.uint8):
return frame
# if floating
elif np.issubdtype(im_type, np.floating):
if (np.min(frame) < -1) or (np.max(frame) > 1):
raise ValueError("Images of type float must be between -1 and 1.")
frame *= 255
frame = np.rint(frame)
frame = np.clip(frame, 0, 255)
return frame.astype(np.uint8)
# if integer
elif np.issubdtype(im_type, np.integer):
im_type_info = np.iinfo(im_type)
frame *= 255 / im_type_info.max
frame[frame < 0] = 0
return frame.astype(np.uint8)
else:
raise TypeError(f"image of type {im_type} could not be converted to ubyte")
def decode_fourcc(cc):
"""
Convert float fourcc code from opencv to characters.
If decode fails, returns empty string.
https://stackoverflow.com/a/49138893
Arguments:
cc (float, int): fourcc code from opencv
Returns:
str: Character format of fourcc code
Examples:
>>> vid = cv2.VideoCapture('/some/video/path.avi')
>>> decode_fourcc(vid.get(cv2.CAP_PROP_FOURCC))
'DIVX'
"""
try:
decoded = "".join([chr((int(cc) >> 8 * i) & 0xFF) for i in range(4)])
except Exception:
decoded = ""
return decoded
def get_available_backends() -> list[Engine]:
"""
Check which backends (TensorFlow or PyTorch) are installed.
Returns:
list[str]: List of installed backends. Possible values: ["tensorflow"], ["pytorch"],
or ["tensorflow", "pytorch"]. Returns an empty list if neither is installed.
Warns:
DLCLiveWarning: If neither TensorFlow nor PyTorch is installed.
"""
backends = []
if get_tensorflow(required=False) is not None:
backends.append(Engine.TENSORFLOW)
if get_torch(required=False) is not None:
backends.append(Engine.PYTORCH)
if not backends:
warnings.warn(
"Neither TensorFlow nor PyTorch is installed. One of these is required to use DLCLive!"
"Install with: pip install deeplabcut-live[tf] or pip install deeplabcut-live[pytorch]",
DLCLiveWarning,
stacklevel=2,
)
return backends
def download_file(url: str, filepath: str, chunk_size: int = 8192) -> None:
"""
Download a file from a URL with progress bar and error handling.
Args:
url: URL to download from
filepath: Local path to save the file
chunk_size: Size of chunks to read (default: 8192 bytes)
Raises:
urllib.error.URLError: If the download fails
IOError: If the file cannot be written
"""
filepath = Path(filepath)
# Check if file already exists
if filepath.exists():
print(f"File already exists at {filepath}, skipping download.")
return
# Ensure parent directory exists
filepath.parent.mkdir(parents=True, exist_ok=True)
try:
# Open the URL
with urllib.request.urlopen(url) as response:
# Get file size if available
total_size = int(response.headers.get("Content-Length", 0))
# Create progress bar if file size is known
if total_size > 0:
pbar = tqdm(total=total_size, unit="B", unit_scale=True, desc="Downloading")
else:
pbar = None
print("Downloading...")
# Download and write file
downloaded = 0
with open(filepath, "wb") as f:
while True:
chunk = response.read(chunk_size)
if not chunk:
break
f.write(chunk)
downloaded += len(chunk)
if pbar:
pbar.update(len(chunk))
if pbar:
pbar.close()
# Verify file was written
if not filepath.exists() or filepath.stat().st_size == 0:
raise OSError(f"Downloaded file is empty or was not written to {filepath}")
print(f"Successfully downloaded to {filepath}")
except urllib.error.HTTPError as e:
raise urllib.error.URLError(f"HTTP error {e.code}: {e.reason} when downloading from {url}") from e
except urllib.error.URLError as e:
raise urllib.error.URLError(f"Failed to download from {url}: {e.reason}") from e
except OSError as e:
raise OSError(f"Failed to write file to {filepath}") from e