Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix typing errors (#2012)

João Gustavo A. Amorimf954d69a5379
diff --git a/kornia/feature/adalam/core.py b/kornia/feature/adalam/core.py
index b318b2344..214c69228 100644
--- a/kornia/feature/adalam/core.py
+++ b/kornia/feature/adalam/core.py
@@ -2,9 +2,8 @@ import math
from typing import Optional, Tuple, Union
import torch
-from torch import tensor
-from kornia.core import Tensor
+from kornia.core import Tensor, concatenate, tensor, where
from .ransac import ransac
from .utils import dist_matrix, orientation_diff
@@ -52,7 +51,7 @@ def select_seeds(dist1: Tensor, R1: Union[float, Tensor], scores1: Tensor, fnn12
im1bs = (~torch.any(im1neighmap & im1scorescomp, dim=1)) & (scores1 < 0.8**2)
# collect all seeds in both images and the 1NN of the seeds of the other image
- im1seeds = torch.where(im1bs)[0] # (n1bs) index format
+ im1seeds = where(im1bs)[0] # (n1bs) index format
im2seeds = fnn12[im1bs] # (n1bs) index format
return im1seeds, im2seeds
@@ -178,7 +177,7 @@ def extract_local_patterns(
# first get an indexing representation of the assignments:
# - ransidx holds the index of the seed for each assignment
# - tokp1 holds the index of the keypoint in image I_1 for each assignment
- ransidx, tokp1 = torch.where(fnn_to_seed_local_consistency_map_corr)
+ ransidx, tokp1 = where(fnn_to_seed_local_consistency_map_corr)
# - and of course tokp2 holds the index of the corresponding keypoint in image I_2
tokp2 = fnn12[tokp1]
@@ -261,18 +260,23 @@ def adalam_core(
SCALE_RATE_THR = config['scale_rate_threshold']
REFIT = config['refit']
- if im1shape is None:
- k1mins, _ = torch.min(k1, dim=0)
- k1maxs, _ = torch.max(k1, dim=0)
- im1shape = k1maxs - k1mins
- if im2shape is None:
- k2mins, _ = torch.min(k2, dim=0)
- k2maxs, _ = torch.max(k2, dim=0)
- im2shape = k2maxs - k2mins
+ if isinstance(im1shape, tuple):
+ _im1shape = tensor(im1shape, device=k1.device, dtype=k1.dtype)
+ else:
+ k1mins = k1.min(dim=0).values
+ k1maxs = k1.max(dim=0).values
+ _im1shape = k1maxs - k1mins
+
+ if isinstance(im2shape, tuple):
+ _im2shape = tensor(im2shape, device=k2.device, dtype=k2.dtype)
+ else:
+ k2mins = k2.min(dim=0).values
+ k2maxs = k2.max(dim=0).values
+ _im2shape = k2maxs - k2mins
# Compute seed selection radii to be invariant to image rescaling
- R1 = torch.sqrt(torch.prod(tensor(im1shape[:2])) / AREA_RATIO / math.pi)
- R2 = torch.sqrt(torch.prod(tensor(im2shape[:2])) / AREA_RATIO / math.pi)
+ R1 = torch.sqrt(torch.prod(_im1shape[:2]) / AREA_RATIO / math.pi)
+ R2 = torch.sqrt(torch.prod(_im2shape[:2]) / AREA_RATIO / math.pi)
# Precompute the inner distances of keypoints in image I_1
dist1 = dist_matrix(k1, k1)
@@ -303,7 +307,7 @@ def adalam_core(
if rdims.shape[0] == 0:
# No seed point survived. Just output ratio-test matches. This should happen very rarely.
score_mask = scores1 <= 0.95
- absolute_im1idx = torch.where(score_mask)[0]
+ absolute_im1idx = where(score_mask)[0]
if len(absolute_im1idx) > 0:
absolute_im2idx = fnn12[absolute_im1idx]
out_scores = scores1[score_mask].reshape(-1, 1)
@@ -343,7 +347,7 @@ def adalam_core(
final_matches, idxs, counts = torch.unique(final_matches, dim=0, return_inverse=True, return_counts=True)
_, ind_sorted = torch.sort(idxs)
cum_sum = counts.cumsum(0)
- cum_sum = torch.cat((torch.tensor([0], dtype=cum_sum.dtype, device=cum_sum.device), cum_sum[:-1]))
+ cum_sum = concatenate((torch.tensor([0], dtype=cum_sum.dtype, device=cum_sum.device), cum_sum[:-1]))
first_indicies = ind_sorted[cum_sum]
accepted_dist = accepted_dist[first_indicies]
if return_dist:
diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.py
index 7a269c786..ee5bed195 100644
--- a/kornia/feature/sold2/sold2.py
+++ b/kornia/feature/sold2/sold2.py
@@ -1,12 +1,13 @@
-from typing import Dict, Optional, Tuple
+from typing import TYPE_CHECKING, Dict, Optional, Tuple
import torch
-import torch.nn as nn
import torch.nn.functional as F
-from torch import Tensor
+from kornia.core import Module, Tensor, concatenate, pad, stack
from kornia.geometry.conversions import normalize_pixel_coordinates
from kornia.testing import KORNIA_CHECK_SHAPE
+from kornia.utils import map_location_to_cpu
+from packaging import version
from .backbones import SOLD2Net
from .sold2_detector import LineSegmentDetectionModule, line_map_to_segments, prob_to_junctions
@@ -49,7 +50,7 @@ default_cfg: Dict = {
}
-class SOLD2(nn.Module):
+class SOLD2(Module):
r"""Module, which detects and describe line segments in an image.
This is based on the original code from the paper "SOLD²: Self-supervised
@@ -86,9 +87,7 @@ class SOLD2(nn.Module):
# Load the pre-trained model
self.model = SOLD2Net(self.config)
if pretrained:
- pretrained_dict = torch.hub.load_state_dict_from_url(
- urls["wireframe"], map_location=lambda storage, loc: storage
- )
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls["wireframe"], map_location=map_location_to_cpu)
state_dict = self.adapt_state_dict(pretrained_dict['model_state_dict'])
self.model.load_state_dict(state_dict)
self.eval()
@@ -156,7 +155,7 @@ class SOLD2(nn.Module):
return state_dict
-class WunschLineMatcher(nn.Module):
+class WunschLineMatcher(Module):
"""Class matching two sets of line segments with the Needleman-Wunsch algorithm.
TODO: move it later in kornia.feature.matching
@@ -254,10 +253,10 @@ class WunschLineMatcher(nn.Module):
cur_line_seg = line_seg[cur_mask]
line_points_x = batched_linspace(cur_line_seg[:, 0, 0], cur_line_seg[:, 1, 0], n_samp, dim=-1)
line_points_y = batched_linspace(cur_line_seg[:, 0, 1], cur_line_seg[:, 1, 1], n_samp, dim=-1)
- cur_line_points = torch.stack([line_points_x, line_points_y], dim=-1)
+ cur_line_points = stack([line_points_x, line_points_y], -1)
# Pad
- cur_line_points = F.pad(cur_line_points, (0, 0, 0, self.num_samples - n_samp))
+ cur_line_points = pad(cur_line_points, (0, 0, 0, self.num_samples - n_samp))
cur_valid_points = torch.ones(len(cur_line_seg), self.num_samples, dtype=torch.bool)
cur_valid_points[:, n_samp:] = False
@@ -288,10 +287,18 @@ class WunschLineMatcher(nn.Module):
line_scores = (line_scores1 + line_scores2) / 2
topk_lines = torch.argsort(line_scores, dim=1)[:, -self.top_k_candidates :]
# topk_lines.shape = (n_lines1, top_k_candidates)
- top_scores = torch.take_along_dim(scores, topk_lines[:, :, None, None], dim=1)
+
+ if TYPE_CHECKING:
+ # TODO: remove this branch if kornia relies on torch>=1.9
+ top_scores: Tensor
+ else:
+ if version.parse(torch.__version__) >= version.parse('1.9.0'):
+ top_scores = torch.take_along_dim(scores, topk_lines[:, :, None, None], dim=1)
+ else:
+ NotImplementedError('This method just work with pytorch newer than 1.9.0')
# Consider the reversed line segments as well
- top_scores = torch.cat([top_scores, torch.flip(top_scores, dims=[-1])], dim=1)
+ top_scores = concatenate([top_scores, torch.flip(top_scores, dims=[-1])], 1)
# Compute the line distance matrix with Needleman-Wunsch algo and
# retrieve the closest line neighbor
diff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.py
index f3a0fe28c..9b98dd842 100644
--- a/kornia/feature/sold2/sold2_detector.py
+++ b/kornia/feature/sold2/sold2_detector.py
@@ -2,12 +2,11 @@ import math
from typing import Dict, Optional, Tuple
import torch
-import torch.nn as nn
-from torch import Tensor, tensor
+from kornia.core import Module, Tensor, concatenate, stack, tensor, where, zeros
from kornia.geometry.bbox import nms
from kornia.testing import KORNIA_CHECK_SHAPE
-from packaging import version
+from kornia.utils import map_location_to_cpu, torch_meshgrid
from .backbones import SOLD2Net
@@ -42,7 +41,7 @@ default_detector_cfg = {
}
-class SOLD2_detector(nn.Module):
+class SOLD2_detector(Module):
r"""Module, which detects line segments in an image.
This is based on the original code from the paper "SOLD²: Self-supervised
@@ -73,9 +72,7 @@ class SOLD2_detector(nn.Module):
# Load the pre-trained model
self.model = SOLD2Net(self.config)
if pretrained:
- pretrained_dict = torch.hub.load_state_dict_from_url(
- urls["wireframe"], map_location=lambda storage, loc: storage
- )
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls["wireframe"], map_location=map_location_to_cpu)
state_dict = self.adapt_state_dict(pretrained_dict['model_state_dict'])
self.model.load_state_dict(state_dict)
self.eval()
@@ -216,7 +213,7 @@ class LineSegmentDetectionModule:
# Initialize empty line map
num_junctions = len(junctions)
- line_map_pred = torch.zeros([num_junctions, num_junctions], device=device, dtype=torch.int32)
+ line_map_pred = zeros([num_junctions, num_junctions], device=device, dtype=torch.int32)
# Stop if there are not enough junctions
if num_junctions < 2:
@@ -232,8 +229,8 @@ class LineSegmentDetectionModule:
candidate_map = self.candidate_suppression(junctions, candidate_map)
# Fetch the candidates
- candidate_indices = torch.where(candidate_map)
- candidate_index_map = torch.cat([candidate_indices[0][..., None], candidate_indices[1][..., None]], dim=-1)
+ candidate_indices = where(candidate_map)
+ candidate_index_map = concatenate([candidate_indices[0][..., None], candidate_indices[1][..., None]], -1)
# Get the corresponding start and end junctions
candidate_junc_start = junctions[candidate_index_map[:, 0]]
@@ -272,7 +269,7 @@ class LineSegmentDetectionModule:
normalized_seg_length_ = normalized_seg_length[iter_idx * group_size :]
sampled_feat_ = self.detect_local_max(heatmap, cand_h_, cand_w_, H, W, normalized_seg_length_, device)
sampled_feat_lst.append(sampled_feat_)
- sampled_feat = torch.cat(sampled_feat_lst, dim=0)
+ sampled_feat = concatenate(sampled_feat_lst, 0)
else:
sampled_feat = self.detect_local_max(heatmap, cand_h, cand_w, H, W, normalized_seg_length, device)
@@ -323,8 +320,8 @@ class LineSegmentDetectionModule:
w_block = round(W / (1 + (num_blocks - 1) * increase_ratio))
# Iterate through each block
- count_map = torch.zeros(heatmap.shape, dtype=torch.int, device=heatmap.device)
- heatmap_output = torch.zeros(heatmap.shape, dtype=torch.float, device=heatmap.device)
+ count_map = zeros(heatmap.shape, dtype=torch.int, device=heatmap.device)
+ heatmap_output = zeros(heatmap.shape, dtype=torch.float, device=heatmap.device)
for h_idx in range(num_blocks):
for w_idx in range(num_blocks):
# Fetch the heatmap
@@ -354,7 +351,7 @@ class LineSegmentDetectionModule:
line_dist_map = torch.sum((torch.unsqueeze(junctions, dim=1) - junctions[None, ...]) ** 2, dim=-1) ** 0.5
# Fetch all the "detected lines"
- seg_indexes = torch.where(torch.triu(candidate_map, diagonal=1))
+ seg_indexes = where(torch.triu(candidate_map, diagonal=1))
start_point_idxs = seg_indexes[0]
end_point_idxs = seg_indexes[1]
start_points = junctions[start_point_idxs, :]
@@ -407,22 +404,21 @@ class LineSegmentDetectionModule:
step=perturb_interval,
device=device,
)
- if version.parse(torch.__version__) < version.parse('1.10'):
- h1_grid, w1_grid, h2_grid, w2_grid = torch.meshgrid(perturb_vec, perturb_vec, perturb_vec, perturb_vec)
- else:
- h1_grid, w1_grid, h2_grid, w2_grid = torch.meshgrid(
- perturb_vec, perturb_vec, perturb_vec, perturb_vec, indexing='ij'
- )
- perturb_tensor = torch.cat(
- [h1_grid[..., None], w1_grid[..., None], h2_grid[..., None], w2_grid[..., None]], dim=-1
+
+ h1_grid, w1_grid, h2_grid, w2_grid = torch_meshgrid(
+ [perturb_vec, perturb_vec, perturb_vec, perturb_vec], indexing='ij'
+ )
+
+ perturb_tensor = concatenate(
+ [h1_grid[..., None], w1_grid[..., None], h2_grid[..., None], w2_grid[..., None]], -1
)
perturb_tensor_flat = perturb_tensor.view(-1, 2, 2)
# Fetch all the detected lines
- detected_seg_indexes = torch.where(torch.triu(line_map, diagonal=1))
+ detected_seg_indexes = where(torch.triu(line_map, diagonal=1))
start_points = junctions[detected_seg_indexes[0]]
end_points = junctions[detected_seg_indexes[1]]
- line_segments = torch.stack([start_points, end_points], dim=1)
+ line_segments = stack([start_points, end_points], 1)
line_segment_candidates = line_segments.unsqueeze(dim=1) + perturb_tensor_flat[None]
# Clip the boundaries
@@ -454,10 +450,10 @@ class LineSegmentDetectionModule:
refined_segment_lst.append(segment[max_idx][None])
# Concatenate back to segments
- refined_segments = torch.cat(refined_segment_lst, dim=0)
+ refined_segments = concatenate(refined_segment_lst, 0)
# Convert back to junctions and line_map
- junctions_new = torch.cat([refined_segments[:, 0, :], refined_segments[:, 1, :]], dim=0)
+ junctions_new = concatenate([refined_segments[:, 0, :], refined_segments[:, 1, :]], 0)
junctions_new = torch.unique(junctions_new, dim=0)
line_map_new = self.segments_to_line_map(junctions_new, refined_segments)
@@ -467,11 +463,11 @@ class LineSegmentDetectionModule:
"""Convert the list of segments to line map."""
# Create empty line map
num_junctions = len(junctions)
- line_map = torch.zeros([num_junctions, num_junctions], device=junctions.device)
+ line_map = zeros([num_junctions, num_junctions], device=junctions.device)
# Get the indices of paired junctions
- _, idx_junc1 = torch.where(torch.all(junctions[None] == segments[:, None, 0], dim=2))
- _, idx_junc2 = torch.where(torch.all(junctions[None] == segments[:, None, 1], dim=2))
+ _, idx_junc1 = where(torch.all(junctions[None] == segments[:, None, 0], dim=2))
+ _, idx_junc2 = where(torch.all(junctions[None] == segments[:, None, 1], dim=2))
# Assign the labels
line_map[idx_junc1, idx_junc2] = 1
@@ -514,16 +510,14 @@ class LineSegmentDetectionModule:
dist_thresh = torch.repeat_interleave(dist_thresh[..., None], self.num_samples, dim=-1)
# Compute the candidate points
- cand_points = torch.cat([cand_h[..., None], cand_w[..., None]], dim=-1)
+ cand_points = concatenate([cand_h[..., None], cand_w[..., None]], -1)
cand_points_round = torch.round(cand_points) # N x 64 x 2
# Construct local patches 9x9 = 81
- patch_mask = torch.zeros(
- [int(2 * self.local_patch_radius + 1), int(2 * self.local_patch_radius + 1)], device=device
- )
+ patch_mask = zeros([int(2 * self.local_patch_radius + 1), int(2 * self.local_patch_radius + 1)], device=device)
patch_center = tensor([[self.local_patch_radius, self.local_patch_radius]], device=device, dtype=torch.float32)
- H_patch_points, W_patch_points = torch.where(patch_mask >= 0)
- patch_points = torch.cat([H_patch_points[..., None], W_patch_points[..., None]], dim=-1)
+ H_patch_points, W_patch_points = where(patch_mask >= 0)
+ patch_points = concatenate([H_patch_points[..., None], W_patch_points[..., None]], -1)
# Fetch the circle region
patch_center_dist = torch.sqrt(torch.sum((patch_points - patch_center) ** 2, dim=-1))
patch_points = patch_points[patch_center_dist <= self.local_patch_radius, :]
@@ -538,7 +532,7 @@ class LineSegmentDetectionModule:
# Get all points => num_points_center x num_patch_points x 2
points_H = torch.clamp(patch_points_shifted[:, :, :, 0], min=0, max=H - 1).to(torch.long)
points_W = torch.clamp(patch_points_shifted[:, :, :, 1], min=0, max=W - 1).to(torch.long)
- points = torch.cat([points_H[..., None], points_W[..., None]], dim=-1)
+ points = concatenate([points_H[..., None], points_W[..., None]], -1)
# Sample the feature (N x 64 x 81)
sampled_feat = heatmap[points[:, :, :, 0], points[:, :, :, 1]]
@@ -554,20 +548,20 @@ class LineSegmentDetectionModule:
def line_map_to_segments(junctions: Tensor, line_map: Tensor) -> Tensor:
"""Convert a junction connectivity map to a Nx2x2 tensor of segments."""
- junc_loc1, junc_loc2 = torch.where(torch.triu(line_map))
- segments = torch.stack([junctions[junc_loc1], junctions[junc_loc2]], dim=1)
+ junc_loc1, junc_loc2 = where(torch.triu(line_map))
+ segments = stack([junctions[junc_loc1], junctions[junc_loc2]], 1)
return segments
def prob_to_junctions(prob: Tensor, dist: float, prob_thresh: float = 0.01, top_k: int = 0) -> Tensor:
"""Extract junctions from a probability map, apply NMS, and extract the top k candidates."""
# Extract the junctions
- junctions = torch.stack(torch.where(prob >= prob_thresh), dim=-1).float()
+ junctions = stack(where(prob >= prob_thresh), -1).float()
if len(junctions) == 0:
return junctions
# Perform NMS
- boxes = torch.cat([junctions - dist / 2, junctions + dist / 2], dim=1)
+ boxes = concatenate([junctions - dist / 2, junctions + dist / 2], 1)
scores = prob[prob >= prob_thresh]
remainings = nms(boxes, scores, 0.001)
junctions = junctions[remainings]
diff --git a/kornia/filters/dexined.py b/kornia/filters/dexined.py
index 9a0c70f12..1d2554092 100644
--- a/kornia/filters/dexined.py
+++ b/kornia/filters/dexined.py
@@ -5,6 +5,9 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
+from kornia.core import Module, Tensor, concatenate
+from kornia.utils import map_location_to_cpu
+
url: str = "http://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth"
@@ -31,7 +34,7 @@ def weight_init(m):
torch.nn.init.zeros_(m.bias)
-class CoFusion(nn.Module):
+class CoFusion(Module):
def __init__(self, in_ch, out_ch):
super().__init__()
self.conv1 = nn.Conv2d(in_ch, 64, kernel_size=3, stride=1, padding=1)
@@ -41,7 +44,7 @@ class CoFusion(nn.Module):
self.norm_layer1 = nn.GroupNorm(4, 64)
self.norm_layer2 = nn.GroupNorm(4, 64)
- def forward(self, x: torch.Tensor) -> torch.Tensor:
+ def forward(self, x: Tensor) -> Tensor:
# fusecat = torch.cat(x, dim=1)
attn = self.relu(self.norm_layer1(self.conv1(x)))
attn = self.relu(self.norm_layer2(self.conv2(attn)))
@@ -63,9 +66,9 @@ class _DenseLayer(nn.Sequential):
self.add_module('conv2', nn.Conv2d(out_features, out_features, kernel_size=3, stride=1, bias=True)),
self.add_module('norm2', nn.BatchNorm2d(out_features))
- def forward(self, x: List[torch.Tensor]) -> List[torch.Tensor]:
+ def forward(self, x: List[Tensor]) -> List[Tensor]:
x1, x2 = x[0], x[1]
- x3: torch.Tensor = x1
+ x3: Tensor = x1
for mod in self:
x3 = mod(x3)
return [0.5 * (x3 + x2), x2]
@@ -79,14 +82,14 @@ class _DenseBlock(nn.Sequential):
self.add_module('denselayer%d' % (i + 1), layer)
input_features = out_features
- def forward(self, x: List[torch.Tensor]) -> List[torch.Tensor]:
+ def forward(self, x: List[Tensor]) -> List[Tensor]:
x_out = x
for mod in self:
x_out = mod(x_out)
return x_out
-class UpConvBlock(nn.Module):
+class UpConvBlock(Module):
def __init__(self, in_features, up_scale):
super().__init__()
self.up_factor = 2
@@ -113,21 +116,21 @@ class UpConvBlock(nn.Module):
def compute_out_features(self, idx, up_scale):
return 1 if idx == up_scale - 1 else self.constant_features
- def forward(self, x: torch.Tensor, out_shape: List[int]) -> torch.Tensor:
+ def forward(self, x: Tensor, out_shape: List[int]) -> Tensor:
out = self.features(x)
if out.shape[-2:] != out_shape:
out = F.interpolate(out, out_shape, mode='bilinear')
return out
-class SingleConvBlock(nn.Module):
+class SingleConvBlock(Module):
def __init__(self, in_features, out_features, stride, use_bs=True):
super().__init__()
self.use_bn = use_bs
self.conv = nn.Conv2d(in_features, out_features, 1, stride=stride, bias=True)
self.bn = nn.BatchNorm2d(out_features)
- def forward(self, x: torch.Tensor) -> torch.Tensor:
+ def forward(self, x: Tensor) -> Tensor:
x = self.conv(x)
if self.use_bn:
x = self.bn(x)
@@ -148,7 +151,7 @@ class DoubleConvBlock(nn.Sequential):
self.add_module("relu2", nn.ReLU(inplace=True))
-class DexiNed(nn.Module):
+class DexiNed(Module):
r"""Definition of the DXtrem network from :cite:`xsoria2020dexined`.
Return:
@@ -204,11 +207,11 @@ class DexiNed(nn.Module):
def load_from_file(self, path_file: str):
# use torch.hub to load pretrained model
- pretrained_dict = torch.hub.load_state_dict_from_url(path_file, map_location=torch.device("cpu"))
+ pretrained_dict = torch.hub.load_state_dict_from_url(path_file, map_location=map_location_to_cpu)
self.load_state_dict(pretrained_dict, strict=True)
self.eval()
- def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
+ def forward(self, x: Tensor) -> List[Tensor]:
# Block 1
block_1 = self.block_1(x)
block_1_side = self.side_1(block_1)
@@ -254,7 +257,7 @@ class DexiNed(nn.Module):
results = [out_1, out_2, out_3, out_4, out_5, out_6]
# concatenate multiscale outputs
- block_cat = torch.cat(results, dim=1) # Bx6xHxW
+ block_cat = concatenate(results, 1) # Bx6xHxW
block_cat = self.block_cat(block_cat) # Bx1xHxW
# return results
diff --git a/kornia/geometry/calibration/pnp.py b/kornia/geometry/calibration/pnp.py
index 21a5374d7..c93ac7613 100644
--- a/kornia/geometry/calibration/pnp.py
+++ b/kornia/geometry/calibration/pnp.py
@@ -1,11 +1,11 @@
from typing import Optional, Tuple
import torch
+from torch.linalg import qr as linalg_qr
from kornia.geometry.conversions import convert_points_to_homogeneous
from kornia.geometry.linalg import transform_points
from kornia.utils import eye_like
-from kornia.utils._compat import linalg_qr
from kornia.utils.helpers import _torch_linalg_svdvals
diff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.py
index 701b60d6f..2a3744974 100644
--- a/kornia/geometry/epipolar/projection.py
+++ b/kornia/geometry/epipolar/projection.py
@@ -2,9 +2,9 @@
from typing import Tuple, Union
import torch
+from torch.linalg import qr as linalg_qr
from kornia.utils import eye_like, vec_like
-from kornia.utils._compat import linalg_qr
from kornia.utils.helpers import _torch_svd_cast
from .numeric import cross_product_matrix
diff --git a/kornia/geometry/vector.py b/kornia/geometry/vector.py
index 04126eb89..b8d348f4c 100644
--- a/kornia/geometry/vector.py
+++ b/kornia/geometry/vector.py
@@ -1,4 +1,4 @@
-from typing import List
+from typing import List, Union
from kornia.core import Module, Parameter, Tensor, normalize, rand
from kornia.geometry.linalg import batched_dot_product
@@ -58,10 +58,11 @@ class _VectorType(Module):
class UnitVector(Module):
- def __init__(self, vector: Tensor) -> None:
+ def __init__(self, vector: Union[Tensor, _VectorType]) -> None:
super().__init__()
KORNIA_CHECK_SHAPE(vector, ["B", "N"])
- self._vector = Parameter(vector)
+ if isinstance(vector, Tensor):
+ self._vector = Parameter(vector)
@property
def vector(self) -> Tensor:
diff --git a/kornia/nerf/data_utils.py b/kornia/nerf/data_utils.py
index 2a16d6e9d..84a0c9661 100755
--- a/kornia/nerf/data_utils.py
+++ b/kornia/nerf/data_utils.py
@@ -1,10 +1,10 @@
-from typing import List, Optional, Sequence, Tuple, Union
+from typing import TYPE_CHECKING, List, Optional, Sequence, Tuple, Union
import torch
from torch.utils.data import BatchSampler, DataLoader, Dataset, RandomSampler, SequentialSampler
from typing_extensions import TypeGuard
-from kornia.core import Device, Tensor
+from kornia.core import Device, Tensor, stack
from kornia.geometry.camera import PinholeCamera
from kornia.io import ImageLoadType, load_image
from kornia.nerf.core import Images, ImageTensors
@@ -146,9 +146,7 @@ class RayDataset(Dataset):
points_2d = self._ray_sampler.points_2d[idxs]
rgbs = None
imgs_for_ids = [self._imgs[i] for i in camerd_ids]
- rgbs = torch.stack(
- [img[:, point2d[1].item(), point2d[0].item()] for img, point2d in zip(imgs_for_ids, points_2d)]
- )
+ rgbs = stack([img[:, point2d[1].item(), point2d[0].item()] for img, point2d in zip(imgs_for_ids, points_2d)])
rgbs = rgbs.to(dtype=self._dtype) / 255.0
return origins, directions, rgbs
@@ -165,10 +163,14 @@ def instantiate_ray_dataloader(dataset: RayDataset, batch_size: int = 1, shuffle
def collate_rays(items: List[RayGroup]) -> RayGroup:
return items[0]
- return DataLoader(
- dataset,
- sampler=BatchSampler(
- RandomSampler(dataset) if shuffle else SequentialSampler(dataset), batch_size, drop_last=False
- ),
- collate_fn=collate_rays,
- )
+ if TYPE_CHECKING:
+ # TODO: remove the type ignore when kornia relies on kornia 1.9.0
+ return DataLoader(dataset)
+ else:
+ return DataLoader(
+ dataset,
+ sampler=BatchSampler(
+ RandomSampler(dataset) if shuffle else SequentialSampler(dataset), batch_size, drop_last=False
+ ),
+ collate_fn=collate_rays,
+ )
diff --git a/kornia/utils/__init__.py b/kornia/utils/__init__.py
index caaefa060..114bfa910 100644
--- a/kornia/utils/__init__.py
+++ b/kornia/utils/__init__.py
@@ -1,6 +1,13 @@
+from ._compat import torch_meshgrid
from .draw import draw_convex_polygon, draw_line, draw_rectangle
from .grid import create_meshgrid, create_meshgrid3d
-from .helpers import _extract_device_dtype, get_cuda_device_if_available, safe_inverse_with_mask, safe_solve_with_mask
+from .helpers import (
+ _extract_device_dtype,
+ get_cuda_device_if_available,
+ map_location_to_cpu,
+ safe_inverse_with_mask,
+ safe_solve_with_mask,
+)
from .image import ImageToTensor, image_list_to_tensor, image_to_tensor, tensor_to_image
from .memory import batched_forward
from .misc import eye_like, vec_like
@@ -27,4 +34,6 @@ __all__ = [
"ImageToTensor",
"eye_like",
"vec_like",
+ "torch_meshgrid",
+ "map_location_to_cpu",
]
diff --git a/kornia/utils/_compat.py b/kornia/utils/_compat.py
index b92736498..59f7f2006 100644
--- a/kornia/utils/_compat.py
+++ b/kornia/utils/_compat.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, List, Optional, Tuple
+from typing import TYPE_CHECKING, Callable, ContextManager, List, Optional, Tuple, TypeVar
import torch
from torch import Tensor
@@ -32,33 +32,30 @@ def torch_version_ge(major: int, minor: int, patch: int) -> bool:
return _version >= version.parse(f"{major}.{minor}.{patch}")
-if version.parse(torch_version()) > version.parse("1.7.1"):
- from torch.linalg import qr as linalg_qr
-else:
- from torch import qr as linalg_qr # noqa: F401
-
-
-if torch_version_ge(1, 10, 0):
+if TYPE_CHECKING:
+ # TODO: remove this branch when kornia relies on torch >= 1.10.0
+ def torch_meshgrid(tensors: List[Tensor], indexing: Optional[str] = None) -> Tuple[Tensor, ...]:
+ ...
- if not TYPE_CHECKING:
+else:
+ if torch_version_ge(1, 10, 0):
def torch_meshgrid(tensors: List[Tensor], indexing: str):
return torch.meshgrid(tensors, indexing=indexing)
-else:
-
- if TYPE_CHECKING:
-
- def torch_meshgrid(tensors: List[Tensor], indexing: Optional[str] = None) -> Tuple[Tensor, ...]:
- return torch.meshgrid(tensors)
-
else:
-
+ # TODO: remove this branch when kornia relies on torch >= 1.10.0
def torch_meshgrid(tensors: List[Tensor], indexing: str):
return torch.meshgrid(tensors)
-if torch_version_ge(1, 10, 0):
- torch_inference_mode = torch.inference_mode
+if TYPE_CHECKING:
+ # TODO: remove this branch when kornia relies on torch >= 1.10.0
+ _T = TypeVar('_T')
+ torch_inference_mode: Callable[..., ContextManager[_T]]
else:
- torch_inference_mode = torch.no_grad
+ if torch_version_ge(1, 10, 0):
+ torch_inference_mode = torch.inference_mode
+ else:
+ # TODO: remove this branch when kornia relies on torch >= 1.10.0
+ torch_inference_mode = torch.no_grad
diff --git a/kornia/utils/grid.py b/kornia/utils/grid.py
index 2cfb2c101..199910661 100644
--- a/kornia/utils/grid.py
+++ b/kornia/utils/grid.py
@@ -1,8 +1,8 @@
from typing import Optional
import torch
-from torch import Tensor, stack
+from kornia.core import Tensor, stack
from kornia.utils._compat import torch_meshgrid
diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.py
index 5a570f5e5..d7a44191e 100644
--- a/kornia/utils/helpers.py
+++ b/kornia/utils/helpers.py
@@ -1,7 +1,7 @@
import warnings
from functools import partial, wraps
from inspect import isclass, isfunction
-from typing import Any, Callable, List, Optional, Tuple
+from typing import TYPE_CHECKING, Any, Callable, List, Optional, Tuple
import torch
@@ -28,6 +28,10 @@ def get_cuda_device_if_available(index: int = 0) -> torch.device:
return dev
+def map_location_to_cpu(storage: str, *args: Any, **kwargs: Any) -> str:
+ return storage
+
+
def _deprecated(func: Optional[Callable] = None, replace_with: Optional[str] = None):
if func is None:
return partial(_deprecated, replace_with=replace_with)
@@ -146,10 +150,16 @@ def _torch_linalg_svdvals(input: Tensor) -> Tensor:
dtype: torch.dtype = input.dtype
if dtype not in (torch.float32, torch.float64):
dtype = torch.float32
- if torch_version_geq(1, 10):
- out = torch.linalg.svdvals(input.to(dtype))
+
+ if TYPE_CHECKING:
+ # TODO: remove this branch when kornia relies on torch >= 1.10
+ out: Tensor
else:
- _, out, _ = torch.linalg.svd(input.to(dtype))
+ if torch_version_geq(1, 10):
+ out = torch.linalg.svdvals(input.to(dtype))
+ else:
+ # TODO: remove this branch when kornia relies on torch >= 1.10
+ _, out, _ = torch.linalg.svd(input.to(dtype))
return out.to(input.dtype)
@@ -182,10 +192,18 @@ def safe_solve_with_mask(B: Tensor, A: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
dtype: torch.dtype = B.dtype
if dtype not in (torch.float32, torch.float64):
dtype = torch.float32
- if not torch_version_geq(1, 13):
- A_LU, pivots, info = torch.lu(A.to(dtype), True, get_infos=True)
+
+ if TYPE_CHECKING:
+ # TODO: remove this branch when kornia relies on torch >= 1.13
+ A_LU: Tensor
+ pivots: Tensor
+ info: Tensor
else:
- A_LU, pivots, info = torch.linalg.lu_factor_ex(A.to(dtype))
+ if torch_version_geq(1, 13):
+ A_LU, pivots, info = torch.linalg.lu_factor_ex(A.to(dtype))
+ else:
+ # TODO: remove this branch when kornia relies on torch >= 1.13
+ A_LU, pivots, info = torch.lu(A.to(dtype), True, get_infos=True)
valid_mask: Tensor = info == 0
n_dim_B = len(B.shape)
@@ -193,10 +211,16 @@ def safe_solve_with_mask(B: Tensor, A: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
if n_dim_A - n_dim_B == 1:
B = B.unsqueeze(-1)
- if not torch_version_geq(1, 13):
- X = torch.lu_solve(B.to(dtype), A_LU, pivots)
+ if TYPE_CHECKING:
+ # TODO: remove this branch when kornia relies on torch >= 1.13
+ X: Tensor
else:
- X = torch.linalg.lu_solve(A_LU, pivots, B.to(dtype))
+ if torch_version_geq(1, 13):
+ X = torch.linalg.lu_solve(A_LU, pivots, B.to(dtype))
+ else:
+ # TODO: remove this branch when kornia relies on torch >= 1.13
+ X = torch.lu_solve(B.to(dtype), A_LU, pivots)
+
return X.to(B.dtype), A_LU.to(A.dtype), valid_mask
@@ -208,15 +232,26 @@ def safe_inverse_with_mask(A: Tensor) -> Tuple[Tensor, Tensor]:
inv = _torch_inverse_cast(A)
warnings.warn('PyTorch version < 1.9, inverse validness mask maybe not correct', RuntimeWarning)
return inv, torch.ones(len(A), dtype=torch.bool, device=A.device)
+
if not isinstance(A, Tensor):
raise AssertionError(f"A must be Tensor. Got: {type(A)}.")
- dtype_original: torch.dtype = A.dtype
+
+ dtype_original = A.dtype
if dtype_original not in (torch.float32, torch.float64):
dtype = torch.float32
else:
dtype = dtype_original
- from torch.linalg import inv_ex # (not available in 1.8.1)
- inverse, info = inv_ex(A.to(dtype))
- mask = info == 0
- return inverse.to(dtype_original), mask
+ if TYPE_CHECKING:
+ # TODO: remove this branch when kornia relies on torch >= 1.9
+ dummy: Tensor = torch.tensor(0)
+ return dummy, dummy
+ else:
+ if torch_version_geq(1, 9):
+ from torch.linalg import inv_ex # (not available in 1.8)
+
+ inverse, info = inv_ex(A.to(dtype))
+ mask = info == 0
+ return inverse.to(dtype_original), mask
+ else:
+ NotImplementedError('This function just work with pytorch newer than 1.9.0')
diff --git a/kornia/utils/one_hot.py b/kornia/utils/one_hot.py
index bfb37ebae..593179033 100644
--- a/kornia/utils/one_hot.py
+++ b/kornia/utils/one_hot.py
@@ -1,15 +1,9 @@
-from typing import Optional
-
import torch
+from kornia.core import Tensor, zeros
+
-def one_hot(
- labels: torch.Tensor,
- num_classes: int,
- device: Optional[torch.device] = None,
- dtype: Optional[torch.dtype] = None,
- eps: float = 1e-6,
-) -> torch.Tensor:
+def one_hot(labels: Tensor, num_classes: int, device: torch.device, dtype: torch.dtype, eps: float = 1e-6) -> Tensor:
r"""Convert an integer label x-D tensor to a one-hot (x+1)-D tensor.
Args:
@@ -24,7 +18,7 @@ def one_hot(
Examples:
>>> labels = torch.LongTensor([[[0, 1], [2, 0]]])
- >>> one_hot(labels, num_classes=3)
+ >>> one_hot(labels, num_classes=3, device=torch.device('cpu'), dtype=torch.int64)
tensor([[[[1.0000e+00, 1.0000e-06],
[1.0000e-06, 1.0000e+00]],
<BLANKLINE>
@@ -34,8 +28,8 @@ def one_hot(
[[1.0000e-06, 1.0000e-06],
[1.0000e+00, 1.0000e-06]]]])
"""
- if not isinstance(labels, torch.Tensor):
- raise TypeError(f"Input labels type is not a torch.Tensor. Got {type(labels)}")
+ if not isinstance(labels, Tensor):
+ raise TypeError(f"Input labels type is not a Tensor. Got {type(labels)}")
if not labels.dtype == torch.int64:
raise ValueError(f"labels must be of the same dtype torch.int64. Got: {labels.dtype}")
@@ -44,6 +38,6 @@ def one_hot(
raise ValueError("The number of classes must be bigger than one." " Got: {}".format(num_classes))
shape = labels.shape
- one_hot = torch.zeros((shape[0], num_classes) + shape[1:], device=device, dtype=dtype)
+ one_hot = zeros((shape[0], num_classes) + shape[1:], device=device, dtype=dtype)
return one_hot.scatter_(1, labels.unsqueeze(1), 1.0) + eps
diff --git a/test/utils/test_one_hot.py b/test/utils/test_one_hot.py
index 3c3b3d381..0a3c56866 100644
--- a/test/utils/test_one_hot.py
+++ b/test/utils/test_one_hot.py
@@ -5,7 +5,7 @@ from kornia.testing import assert_close
class TestOneHot:
- def test_smoke(self):
+ def test_smoke(self, device, dtype):
num_classes = 4
labels = torch.zeros(2, 2, 1, dtype=torch.int64)
labels[0, 0, 0] = 0
@@ -14,7 +14,7 @@ class TestOneHot:
labels[1, 1, 0] = 3
# convert labels to one hot tensor
- one_hot = kornia.utils.one_hot(labels, num_classes)
+ one_hot = kornia.utils.one_hot(labels, num_classes, device, dtype)
assert_close(one_hot[0, labels[0, 0, 0], 0, 0].item(), 1.0)
assert_close(one_hot[0, labels[0, 1, 0], 1, 0].item(), 1.0)