Cast the Numpy data to specified numpy data type, or cast the PyTorch Tensor to specified PyTorch data type. Example: >>> import numpy as np >>> import torch >>> transform = CastToType(dtype=np.float32) >>> # Example with a numpy array >>> img_n
| 335 | |
| 336 | |
| 337 | class CastToType(Transform): |
| 338 | """ |
| 339 | Cast the Numpy data to specified numpy data type, or cast the PyTorch Tensor to |
| 340 | specified PyTorch data type. |
| 341 | |
| 342 | Example: |
| 343 | >>> import numpy as np |
| 344 | >>> import torch |
| 345 | >>> transform = CastToType(dtype=np.float32) |
| 346 | |
| 347 | >>> # Example with a numpy array |
| 348 | >>> img_np = np.array([0, 127, 255], dtype=np.uint8) |
| 349 | >>> img_np_casted = transform(img_np) |
| 350 | >>> img_np_casted |
| 351 | array([ 0. , 127. , 255. ], dtype=float32) |
| 352 | |
| 353 | >>> # Example with a PyTorch tensor |
| 354 | >>> img_tensor = torch.tensor([0, 127, 255], dtype=torch.uint8) |
| 355 | >>> img_tensor_casted = transform(img_tensor) |
| 356 | >>> img_tensor_casted |
| 357 | tensor([ 0., 127., 255.]) # dtype is float32 |
| 358 | """ |
| 359 | |
| 360 | backend = [TransformBackends.TORCH, TransformBackends.NUMPY] |
| 361 | |
| 362 | def __init__(self, dtype=np.float32) -> None: |
| 363 | """ |
| 364 | Args: |
| 365 | dtype: convert image to this data type, default is `np.float32`. |
| 366 | """ |
| 367 | self.dtype = dtype |
| 368 | |
| 369 | def __call__(self, img: NdarrayOrTensor, dtype: DtypeLike | torch.dtype = None) -> NdarrayOrTensor: |
| 370 | """ |
| 371 | Apply the transform to `img`, assuming `img` is a numpy array or PyTorch Tensor. |
| 372 | |
| 373 | Args: |
| 374 | dtype: convert image to this data type, default is `self.dtype`. |
| 375 | |
| 376 | Raises: |
| 377 | TypeError: When ``img`` type is not in ``Union[numpy.ndarray, torch.Tensor]``. |
| 378 | |
| 379 | """ |
| 380 | return convert_data_type(img, output_type=type(img), dtype=dtype or self.dtype)[0] |
| 381 | |
| 382 | |
| 383 | class ToTensor(Transform): |
no outgoing calls
searching dependent graphs…