Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[FIX] fix device issue for get_motion_kernel2d (#775)

Guanzhi Wang415c36e2c89d
diff --git a/kornia/augmentation/random_generator/random_generator.py b/kornia/augmentation/random_generator/random_generator.py
index 4719a5a32..db0f2ffe8 100644
--- a/kornia/augmentation/random_generator/random_generator.py
+++ b/kornia/augmentation/random_generator/random_generator.py
@@ -12,8 +12,8 @@ from ..utils import (
_adapted_beta,
_joint_range_check,
_common_param_check,
- _extract_device_dtype,
)
+from kornia.utils import _extract_device_dtype
def random_prob_generator(
diff --git a/kornia/augmentation/random_generator/random_generator3d.py b/kornia/augmentation/random_generator/random_generator3d.py
index 43187619a..8e1af8b15 100644
--- a/kornia/augmentation/random_generator/random_generator3d.py
+++ b/kornia/augmentation/random_generator/random_generator3d.py
@@ -9,8 +9,8 @@ from kornia.geometry import bbox_generator3d
from ..utils import (
_adapted_uniform,
_tuple_range_reader,
- _extract_device_dtype
)
+from kornia.utils import _extract_device_dtype
def random_rotation_generator3d(
diff --git a/kornia/augmentation/utils/__init__.py b/kornia/augmentation/utils/__init__.py
index dbf471251..5ad991aab 100644
--- a/kornia/augmentation/utils/__init__.py
+++ b/kornia/augmentation/utils/__init__.py
@@ -18,7 +18,6 @@ from kornia.augmentation.utils.helpers import (
_adapted_uniform,
_adapted_beta,
_shape_validation,
- _extract_device_dtype,
)
__all__ = [
@@ -34,7 +33,6 @@ __all__ = [
"_adapted_uniform",
"_adapted_beta",
"_shape_validation",
- "_extract_device_dtype",
"_common_param_check",
"_range_bound",
"_joint_range_check",
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index b5321e461..6a971fa60 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -3,6 +3,8 @@ from typing import Tuple, Union, List, cast, Optional
import torch
from torch.distributions import Uniform, Beta
+from kornia.utils import _extract_device_dtype
+
def _infer_batch_shape(input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]) -> torch.Size:
r"""Infer input shape. Input may be either (tensor,) or (tensor, transform_matrix)
@@ -233,24 +235,3 @@ def _check_and_bound(factor: Union[torch.Tensor, float, Tuple[float, float], Lis
def _shape_validation(param: torch.Tensor, shape: Union[tuple, list], name: str) -> None:
assert param.shape == torch.Size(shape), f"Invalid shape for {name}. Expected {shape}. Got {param.shape}"
-
-
-def _extract_device_dtype(tensor_list: List[Optional[torch.Tensor]]):
- """This function will check if all the input tensors are in the same device.
-
- If so, it would return a tuple of (device, dtype)
- """
- device, dtype = None, None
- for tensor in tensor_list:
- if tensor is not None:
- if not isinstance(tensor, (torch.Tensor,)):
- raise ValueError(f"Expected None or Tensor. Got {tensor}.")
- _device = tensor.device
- _dtype = tensor.dtype
- if device is None and dtype is None:
- device = _device
- dtype = _dtype
- elif device != _device or dtype != _dtype:
- raise ValueError("Passed values are not in the same device and dtype."
- f"Got ({device}, {dtype}) and ({_device}, {_dtype}).")
- return (device, dtype)
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index 717deb6c7..e4937c1ff 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -4,6 +4,7 @@ import torch
from math import sqrt
from kornia.geometry.transform.affwarp import rotate, rotate3d
+from kornia.utils import _extract_device_dtype
def normalize_kernel2d(input: torch.Tensor) -> torch.Tensor:
@@ -641,11 +642,17 @@ def get_motion_kernel2d(kernel_size: int, angle: Union[torch.Tensor, float],
[0.1920, 0.3194, 0.0804],
[0.2195, 0.0743, 0.0000]])
"""
+
+ device, dtype = _extract_device_dtype([
+ angle if isinstance(angle, torch.Tensor) else None,
+ direction if isinstance(direction, torch.Tensor) else None,
+ ])
+
if not isinstance(kernel_size, int) or kernel_size % 2 == 0 or kernel_size < 3:
raise TypeError("ksize must be an odd integer >= than 3")
if not isinstance(angle, torch.Tensor):
- angle = torch.tensor([angle])
+ angle = torch.tensor([angle], device=device, dtype=dtype)
angle = cast(torch.Tensor, angle)
if angle.dim() == 0:
@@ -653,7 +660,7 @@ def get_motion_kernel2d(kernel_size: int, angle: Union[torch.Tensor, float],
assert angle.dim() == 1, f"angle must be a 1-dim tensor. Got {angle}."
if not isinstance(direction, torch.Tensor):
- direction = torch.tensor([direction])
+ direction = torch.tensor([direction], device=device, dtype=dtype)
direction = cast(torch.Tensor, direction)
if direction.dim() == 0:
@@ -666,7 +673,7 @@ def get_motion_kernel2d(kernel_size: int, angle: Union[torch.Tensor, float],
kernel_tuple: Tuple[int, int] = (kernel_size, kernel_size)
# direction from [-1, 1] to [0, 1] range
direction = (torch.clamp(direction, -1., 1.) + 1.) / 2.
- kernel = torch.zeros((direction.size(0), *kernel_tuple), dtype=torch.float)
+ kernel = torch.zeros((direction.size(0), *kernel_tuple), device=device, dtype=dtype)
# Element-wise linspace
kernel[:, kernel_tuple[0] // 2, :] = torch.stack(
diff --git a/kornia/utils/__init__.py b/kornia/utils/__init__.py
index 59c1e7380..b05d4a1fd 100644
--- a/kornia/utils/__init__.py
+++ b/kornia/utils/__init__.py
@@ -2,6 +2,7 @@ from .one_hot import one_hot
from .grid import create_meshgrid, create_meshgrid3d
from .image import tensor_to_image, image_to_tensor
from .pointcloud_io import save_pointcloud_ply, load_pointcloud_ply
+from .helpers import _extract_device_dtype
from kornia.utils.metrics import *
@@ -13,4 +14,5 @@ __all__ = [
"image_to_tensor",
"save_pointcloud_ply",
"load_pointcloud_ply",
+ "_extract_device_dtype",
]
diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.py
new file mode 100644
index 000000000..c1cc83921
--- /dev/null
+++ b/kornia/utils/helpers.py
@@ -0,0 +1,24 @@
+from typing import Tuple, Union, List, cast, Optional
+
+import torch
+
+
+def _extract_device_dtype(tensor_list: List[Optional[torch.Tensor]]):
+ """This function will check if all the input tensors are in the same device.
+
+ If so, it would return a tuple of (device, dtype)
+ """
+ device, dtype = None, None
+ for tensor in tensor_list:
+ if tensor is not None:
+ if not isinstance(tensor, (torch.Tensor,)):
+ raise ValueError(f"Expected None or Tensor. Got {tensor}.")
+ _device = tensor.device
+ _dtype = tensor.dtype
+ if device is None and dtype is None:
+ device = _device
+ dtype = _dtype
+ elif device != _device or dtype != _dtype:
+ raise ValueError("Passed values are not in the same device and dtype."
+ f"Got ({device}, {dtype}) and ({_device}, {_dtype}).")
+ return (device, dtype)