from collections import OrderedDict
import math
import pickle
import zipfile
import numpy as np
from scipy.ndimage import affine_transform, map_coordinates
from dipy.utils.deprecator import warning_for_keywords
[docs]
@warning_for_keywords()
def normalize(image, *, min_v=None, max_v=None, new_min=-1, new_max=1):
"""
normalization function
Parameters
----------
image : np.ndarray
Image to be normalized.
min_v : int or float, optional
minimum value range for normalization
intensities below min_v will be clipped
if None it is set to min value of image
max_v : int or float, optional
maximum value range for normalization
intensities above max_v will be clipped
if None it is set to max value of image
new_min : int or float, optional
new minimum value after normalization
new_max : int or float, optional
new maximum value after normalization
Returns
-------
np.ndarray
Normalized image from range new_min to new_max
"""
if min_v is None:
min_v = np.min(image)
if max_v is None:
max_v = np.max(image)
return np.interp(image, (min_v, max_v), (new_min, new_max))
[docs]
def unnormalize(image, norm_min, norm_max, min_v, max_v):
"""
unnormalization function
Parameters
----------
image : np.ndarray
norm_min : int or float
minimum value of normalized image
norm_max : int or float
maximum value of normalized image
min_v : int or float
minimum value of unnormalized image
max_v : int or float
maximum value of unnormalized image
Returns
-------
np.ndarray
unnormalized image from range min_v to max_v
"""
return (image - norm_min) / (norm_max - norm_min) * (max_v - min_v) + min_v
def set_logger_level(log_level, logger):
"""Change the logger to one of the following:
DEBUG, INFO, WARNING, CRITICAL, ERROR
Parameters
----------
log_level : str
Log level for the logger
"""
logger.setLevel(level=log_level)
[docs]
@warning_for_keywords()
def get_bounds(shape, affine, *, considered_points="corners"):
"""
Function to get the bounds of an image after applying affine
Parameters
----------
shape : tuple (3,)
Shape of the image
affine : np.ndarray
Affine matrix provided by the image file.
considered_points : str, optional
Considered points when calculating the transformed shape.
\"corners\" will consider only corners of the image shape.
\"all\" will consider all voxels.
Might be needed when shearing is applied.
Returns
-------
min_bounds : np.ndarray (3,)
Minimum bounds of the transformed image
max_bounds : np.ndarray (3,)
Maximum bounds of the transformed image
"""
if considered_points == "corners":
points = np.array(
[
[0, 0, 0, 1],
[shape[0] - 1, 0, 0, 1],
[0, shape[1] - 1, 0, 1],
[0, 0, shape[2] - 1, 1],
[shape[0] - 1, shape[1] - 1, shape[2] - 1, 1],
[shape[0] - 1, 0, shape[2] - 1, 1],
[0, shape[1] - 1, shape[2] - 1, 1],
[shape[0] - 1, shape[1] - 1, 0, 1],
],
dtype=np.float64,
)
elif considered_points == "all":
temp1 = np.arange(shape[0])
temp2 = np.arange(shape[1])
temp3 = np.arange(shape[2])
grid1, grid2, grid3 = np.meshgrid(temp1, temp2, temp3)
points = np.vstack([grid1.ravel(), grid2.ravel(), grid3.ravel()]).T
points = np.hstack([points, np.full((points.shape[0], 1), 1)])
points = points.astype(np.float64)
else:
ValueError('considered points should be "corners" or "all"')
transformed_corners = (affine @ points.T).T
min_bounds = transformed_corners.min(axis=0)[:3]
max_bounds = transformed_corners.max(axis=0)[:3]
return min_bounds, max_bounds
[docs]
def recover_img(image, params, *, order=3):
"""
Function to recover image from transform_img
Parameters
----------
image : np.ndarray
Image to recover.
params : dict
Parameters for recover_img function.
Returned from transform_img.
order : int, optional
The order of the spline interpolation.
The order has to be in the range 0-5.
If recovering an int image, order 0 is recommended.
Returns
-------
recovered : np.ndarray
Recovered image
"""
expected = {
"init_shape",
"ori_affine",
"target_voxsize",
"new_origin_world",
"pad_value",
"crop_value",
}
missing = expected - set(params.keys())
if missing:
raise ValueError(f"params missing: {missing}")
init_shape = tuple(int(x) for x in params["init_shape"])
affine = np.asarray(params["ori_affine"], dtype=float)
target_voxsize = np.asarray(params["target_voxsize"], dtype=float)
new_origin_world = np.asarray(params["new_origin_world"], dtype=float)
pad_vs = params["pad_value"]
crop_vs = params["crop_value"]
if crop_vs is not None and pad_vs is not None:
new_image = inv_pad_crop(image, crop_vs, pad_vs)
else:
new_image = image
A = affine
D = np.diag(target_voxsize)
coords_idx = np.indices(init_shape, dtype=float)
coords_idx = coords_idx.reshape((len(init_shape), -1))
world_coords = (A[:3, :3] @ coords_idx) + A[:3, 3][:, None]
coords_new = np.linalg.inv(D) @ (world_coords - new_origin_world[:, None])
coords_for_map = coords_new.reshape((len(init_shape),) + tuple(init_shape))
recovered = map_coordinates(new_image, coords_for_map, order=order)
return recovered
[docs]
def get_padded_shape(shape, multiple):
"""Return the smallest shape greater than or equal to ``shape`` whose
dimensions are divisible by ``multiple``.
Parameters
----------
shape : sequence of int
Input shape.
multiple : int
Value that every output dimension must be divisible by.
Returns
-------
tuple of int
Smallest shape greater than or equal to ``shape`` for which every
dimension is divisible by ``multiple``.
"""
if multiple <= 0:
raise ValueError("multiple must be greater than zero")
return tuple(math.ceil(int(dim) / multiple) * multiple for dim in shape)
[docs]
def pad_crop(image, target_shape):
"""
Function to figure out pad and crop range
to fit the target shape with the image
Parameters
----------
image : np.ndarray
Target image
target_shape : (3,)
Target shape
Returns
-------
image : np.ndarray
Padded/cropped image
pad_vs : np.ndarray (3,2)
Pad range used
crop_vs : np.ndarray (3,2)
Crop range used
"""
crop_vs = np.zeros((3, 2)).astype(int)
pad_vs = np.zeros((3, 2)).astype(int)
if np.all(np.array(image.shape) == target_shape):
return image, pad_vs, crop_vs
pad_crop_v = np.array(target_shape) - np.array(image.shape)
for d in range(3):
if pad_crop_v[d] < 0:
crop_vs[d, 0] = -pad_crop_v[d] // 2
crop_vs[d, 1] = -pad_crop_v[d] - crop_vs[d, 0]
elif pad_crop_v[d] > 0:
pad_vs[d, 0] = pad_crop_v[d] // 2
pad_vs[d, 1] = pad_crop_v[d] - pad_vs[d, 0]
image = np.pad(
image,
(
(pad_vs[0, 0], pad_vs[0, 1]),
(pad_vs[1, 0], pad_vs[1, 1]),
(pad_vs[2, 0], pad_vs[2, 1]),
),
)
image = image[
crop_vs[0, 0] : image.shape[0] - crop_vs[0, 1],
crop_vs[1, 0] : image.shape[1] - crop_vs[1, 1],
crop_vs[2, 0] : image.shape[2] - crop_vs[2, 1],
]
return image, pad_vs, crop_vs
[docs]
def inv_pad_crop(image, crop_vs, pad_vs):
"""
Function to figure out pad and crop range
to fit the target shape with the image
Parameters
----------
image : np.ndarray
Target image
crop_vs : np.ndarray (3,2)
Crop range used when padding/cropping
pad_vs : np.ndarray (3,2)
Pad range used when padding/cropping
Returns
-------
image : np.ndarray
Recovered image
"""
crop_vs = crop_vs.astype(int)
pad_vs = pad_vs.astype(int)
image = np.pad(
image,
(
(crop_vs[0, 0], crop_vs[0, 1]),
(crop_vs[1, 0], crop_vs[1, 1]),
(crop_vs[2, 0], crop_vs[2, 1]),
),
)
image = image[
pad_vs[0, 0] : image.shape[0] - pad_vs[0, 1],
pad_vs[1, 0] : image.shape[1] - pad_vs[1, 1],
pad_vs[2, 0] : image.shape[2] - pad_vs[2, 1],
]
return image
def _rebuild_tensor(storage, offset, size, stride, *args):
"""Rebuild a pickled PyTorch tensor as a NumPy array.
Parameters
----------
storage : np.ndarray
Flat storage of the tensor.
offset : int
Offset of the tensor in the storage, in elements.
size : tuple of int
Shape of the tensor.
stride : tuple of int
Strides of the tensor, in elements.
*args
Gradient and hook metadata, ignored.
Returns
-------
np.ndarray
Copy of the tensor data.
"""
return np.lib.stride_tricks.as_strided(
storage[offset:],
shape=tuple(size),
strides=tuple(s * storage.itemsize for s in stride),
).copy()
_STATE_DICT_GLOBALS = {
("collections", "OrderedDict"): OrderedDict,
("torch._utils", "_rebuild_tensor_v2"): _rebuild_tensor,
("torch", "FloatStorage"): np.float32,
("torch", "DoubleStorage"): np.float64,
("torch", "HalfStorage"): np.float16,
("torch", "IntStorage"): np.int32,
("torch", "LongStorage"): np.int64,
}
class _StateDictUnpickler(pickle.Unpickler):
"""Unpickler rebuilding the tensors of a PyTorch state dict as arrays.
Only the globals listed in ``_STATE_DICT_GLOBALS`` can be loaded, so
reading a file cannot execute arbitrary code.
Parameters
----------
file : file object
Opened pickle of the state dict.
load_storage : callable
Called as ``load_storage(dtype, key, numel)`` for each tensor storage
of the pickle, it returns the storage as a flat array.
"""
def __init__(self, file, *, load_storage):
super().__init__(file)
self.load_storage = load_storage
def find_class(self, module, name):
try:
return _STATE_DICT_GLOBALS[(module, name)]
except KeyError:
raise pickle.UnpicklingError(
f"Unsupported object {module}.{name} in a PyTorch state dict"
) from None
def persistent_load(self, pid):
# The legacy format appends a view metadata field to the zip one.
_, dtype, key, _, numel = pid[:5]
return self.load_storage(np.dtype(dtype).newbyteorder("<"), key, numel)
# First pickle of the files written by torch.save before PyTorch 1.6.
_LEGACY_MAGIC_NUMBER = 0x1950A86A20F9469CFC6C
_LEGACY_PROTOCOL_VERSION = 1001
def _load_zip_state_dict(fname):
"""Read a state dict in the zip format used by PyTorch since 1.6.
Parameters
----------
fname : str or Path
Path to the file.
Returns
-------
object
Unpickled state dict.
"""
with zipfile.ZipFile(fname) as archive:
pickles = [n for n in archive.namelist() if n.endswith("/data.pkl")]
if len(pickles) != 1:
raise ValueError(f"{fname} is not a PyTorch state dict")
prefix = pickles[0][: -len("/data.pkl")]
def load_storage(dtype, key, numel):
data = archive.read(f"{prefix}/data/{key}")
return np.frombuffer(data, dtype=dtype, count=numel)
with archive.open(pickles[0]) as f:
return _StateDictUnpickler(f, load_storage=load_storage).load()
def _load_legacy_state_dict(fname):
"""Read a state dict in the format used by PyTorch before 1.6.
The file holds a magic number, a protocol version, system information,
the state dict and the list of its storage keys, each as a pickle,
followed by every storage as its number of elements (int64) and its raw
data, in the order of the keys. The storages come after the state dict,
so it is unpickled twice: once to find the type of every storage, then
once with the storages read.
Parameters
----------
fname : str or Path
Path to the file.
Returns
-------
object
Unpickled state dict.
"""
with open(fname, "rb") as f:
header = [_StateDictUnpickler(f, load_storage=None).load() for _ in range(3)]
magic, protocol, sys_info = header
if (
magic != _LEGACY_MAGIC_NUMBER
or protocol != _LEGACY_PROTOCOL_VERSION
or not isinstance(sys_info, dict)
or not sys_info.get("little_endian", False)
):
raise ValueError(f"{fname} is not a PyTorch state dict")
start = f.tell()
dtypes = {}
def record_dtype(dtype, key, numel):
dtypes[key] = dtype
return np.zeros(numel, dtype=dtype)
_StateDictUnpickler(f, load_storage=record_dtype).load()
keys = _StateDictUnpickler(f, load_storage=None).load()
if not isinstance(keys, list) or set(keys) != set(dtypes):
raise ValueError(f"{fname} is not a PyTorch state dict")
storages = {}
for key in keys:
numel = int.from_bytes(f.read(8), "little")
data = f.read(numel * dtypes[key].itemsize)
storages[key] = np.frombuffer(data, dtype=dtypes[key], count=numel)
f.seek(start)
return _StateDictUnpickler(
f, load_storage=lambda dtype, key, numel: storages[key][:numel]
).load()
[docs]
def load_state_dict(fname):
"""Read a PyTorch state dict saved by ``torch.save``, without PyTorch.
Parameters
----------
fname : str or Path
Path to the file, either in the zip format used by PyTorch since 1.6
or in the legacy format used before.
Returns
-------
dict
Parameter names mapped to NumPy arrays.
"""
try:
if zipfile.is_zipfile(fname):
state = _load_zip_state_dict(fname)
else:
state = _load_legacy_state_dict(fname)
except (
zipfile.BadZipFile,
pickle.UnpicklingError,
EOFError,
KeyError,
TypeError,
ValueError,
) as e:
raise ValueError(f"Could not read the PyTorch state dict {fname}") from e
if not isinstance(state, dict):
raise ValueError(f"{fname} is not a PyTorch state dict")
return dict(state)