π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Merged
Jian Sfed0dd86f997
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex 0f42d4a00..1d51dcf5c 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -1 +1,12 @@from .augmentation import *+++__all__ = [+ "RandomHorizontalFlip",+ "RandomVerticalFlip",+ "RandomRectangleErasing",+ "RandomGrayscale",+ "ColorJitter",+ "RandomCrop",+ "RandomResizedCrop"+]diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.pyindex 331a828a5..73799a9d9 100644--- a/kornia/augmentation/augmentation.py+++ b/kornia/augmentation/augmentation.py@@ -1,7 +1,10 @@from typing import Callable, Tuple, Union, List, Optional, Dict, cast+import random+import mathimport torchimport torch.nn as nn+from torch.nn.functional import padfrom . import functional as Ffrom . import param_gen as pg@@ -11,6 +14,7 @@ TupleFloat = Tuple[float, float]UnionFloat = Union[float, TupleFloat]UnionType = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]FloatUnionType = Union[torch.Tensor, float, Tuple[float, float], List[float]]+BoarderUnionType = Union[int, Tuple[int, int], Tuple[int, int, int, int]]class AugmentationBase(nn.Module):@@ -426,3 +430,147 @@ class RandomRotation(AugmentationBase):batch_size: int = self.infer_batch_size(input)params = self.get_params(batch_size, self.degrees)return super().forward(input, params)+++class RandomCrop(AugmentationBase):+ r"""Random Crop on given size.+ Args:+ size (tuple): Desired output size of the crop, like (h, w).+ padding (int or sequence, optional): Optional padding on each border+ of the image. Default is None, i.e no padding. If a sequence of length+ 4 is provided, it is used to pad left, top, right, bottom borders+ respectively. If a sequence of length 2 is provided, it is used to+ pad left/right, top/bottom borders, respectively.+ pad_if_needed (boolean): It will pad the image if smaller than the+ desired size to avoid raising an exception. Since cropping is done+ after padding, the padding seems to be done at a random offset.+ fill: Pixel fill value for constant fill. Default is 0. If a tuple of+ length 3, it is used to fill R, G, B channels respectively.+ This value is only used when the padding_mode is constant+ padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant.+ return_transform (bool): if ``True`` return the matrix describing the transformation applied to each+ input tensor. If ``False`` and the input is a tuple the applied transformation+ wont be concatenated+ """++ def __init__(self, size: Tuple[int, int], padding: Optional[BoarderUnionType] = None,+ pad_if_needed: Optional[bool] = False, fill=0, padding_mode='constant',+ return_transform: bool = False) -> None:+ super(RandomCrop, self).__init__(F.apply_crop, return_transform)+ self.size = size+ self.padding = padding+ self.pad_if_needed = pad_if_needed+ self.fill = fill+ self.padding_mode = padding_mode++ def __repr__(self) -> str:+ repr = f"(crop_size={self.size}, return_transform={self.return_transform})"+ return self.__class__.__name__ + repr++ @staticmethod+ def get_params(batch_size: int, input_size: Tuple[int, int], size: Tuple[int, int]) -> Dict[str, torch.Tensor]:+ return pg._random_crop_gen(batch_size, input_size, size)++ def precrop_padding(self, input: torch.Tensor):++ if self.padding is not None:+ if isinstance(self.padding, int):+ padding = [self.padding, self.padding, self.padding, self.padding]+ elif isinstance(self.padding, tuple) and len(self.padding) == 2:+ padding = [self.padding[1], self.padding[1], self.padding[0], self.padding[0]]+ elif isinstance(self.padding, tuple) and len(self.padding) == 4:+ padding = [self.padding[3], self.padding[2], self.padding[1], self.padding[0]] # type:ignore+ input = pad(input, padding, value=self.fill, mode=self.padding_mode)++ if self.pad_if_needed and input.shape[-2] < self.size[1]:+ padding = [self.size[1] - input.shape[-2], self.size[1] - input.shape[-2], 0, 0]+ input = pad(input, padding, value=self.fill, mode=self.padding_mode)++ if self.pad_if_needed and input.shape[-1] < self.size[0]:+ padding = [0, 0, self.size[0] - input.shape[-1], self.size[0] - input.shape[-1]]+ input = pad(input, padding, value=self.fill, mode=self.padding_mode)++ return input++ def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]] = None) -> UnionType: # type: ignore+ if isinstance(input, tuple):+ batch_shape = input[0].shape+ input = (self.precrop_padding(input[0]), self.precrop_padding(input[1]))+ else:+ batch_shape = input.shape+ input = self.precrop_padding(input)++ if params is None:+ batch_size = self.infer_batch_size(input)+ params = RandomCrop.get_params(batch_size, batch_shape[-2:], self.size) # type: ignore+ return super().forward(input, params)+++class RandomResizedCrop(AugmentationBase):+ r"""Random Crop on given size and resizing the cropped patch to another.+ Args:+ size (Tuple[int, int]): expected output size of each edge+ scale: range of size of the origin size cropped+ ratio: range of aspect ratio of the origin aspect ratio cropped+ interpolation: Default: PIL.Image.BILINEAR+ return_transform (bool): if ``True`` return the matrix describing the transformation applied to each+ input tensor. If ``False`` and the input is a tuple the applied transformation+ wont be concatenated+ """++ def __init__(self, size: Tuple[int, int], scale=(1.0, 1.0), ratio=(1.0, 1.0),+ interpolation=None, return_transform: bool = False) -> None:+ super(RandomResizedCrop, self).__init__(F.apply_crop, return_transform)+ self.size = size+ self.scale = scale+ self.ratio = ratio+ self.interpolation = interpolation+ if interpolation is not None:+ raise ValueError("Interpolation has not been implemented. Please set to None")++ def __repr__(self) -> str:+ repr = f"(size={self.size}, resize_to={self.resize_to}, return_transform={self.return_transform})"+ return self.__class__.__name__ + repr++ @staticmethod+ def get_params(batch_size: int, input_size: Tuple[int, int], size: Tuple[int, int],+ scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.)) -> Dict[str, torch.Tensor]:+ target_size = RandomResizedCrop.get_aspected_size(size, scale, ratio)+ # TODO: scale and aspect ratio were fixed for one batch for now. Need to be separated.+ return pg._random_crop_gen(batch_size, input_size, target_size, resize_to=size)++ @staticmethod+ def get_aspected_size(size, scale, ratio):+ for attempt in range(10):+ target_area = random.uniform(*scale) * size[0] * size[1]+ log_ratio = (math.log(ratio[0]), math.log(ratio[1]))+ aspect_ratio = math.exp(random.uniform(*log_ratio))++ w = int(round(math.sqrt(target_area * aspect_ratio)))+ h = int(round(math.sqrt(target_area / aspect_ratio)))+ if 0 < w < size[0] and 0 < h < size[1]:+ return (w, h)++ # Fallback to center crop+ in_ratio = float(size[0]) / float(size[1])+ if (in_ratio < min(ratio)):+ w = size[0]+ h = int(round(w / min(ratio)))+ elif (in_ratio > max(ratio)):+ h = size[1]+ w = int(round(h * max(ratio)))+ else: # whole image+ w = size[0]+ h = size[1]+ return (w, h)++ def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]] = None) -> UnionType: # type: ignore+ if params is None:+ batch_size = self.infer_batch_size(input)+ if isinstance(input, tuple):+ batch_shape = input[0].shape+ else:+ batch_shape = input.shape+ params = RandomResizedCrop.get_params(+ batch_size, batch_shape[-2:], self.size, self.scale, self.ratio) # type: ignore+ return super().forward(input, params)diff --git a/kornia/augmentation/functional.py b/kornia/augmentation/functional.pyindex d4bbb5db6..45a63f85f 100644--- a/kornia/augmentation/functional.py+++ b/kornia/augmentation/functional.py@@ -4,14 +4,15 @@ import torchimport torch.nn as nnfrom kornia.geometry.transform.flips import hflip, vflip-from kornia.geometry.transform import get_perspective_transform, warp_perspective, center_crop, rotate-from kornia.geometry.transform import get_perspective_transform, warp_perspective, rotate+from kornia.geometry.transform import (+ get_perspective_transform, warp_perspective, center_crop, rotate, crop_by_boxes)from kornia.color.adjust import AdjustBrightness, AdjustContrast, AdjustSaturation, AdjustHuefrom kornia.color.gray import rgb_to_grayscalefrom kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute_tensor_centerfrom . import param_gen as pgfrom .erasing import erase_rectangles, get_random_rectangles_params+from .utils import _transform_input, _validate_input_shapeTupleFloat = Tuple[float, float]@@ -187,17 +188,7 @@ def apply_hflip(input: torch.Tensor, params: Dict[str, torch.Tensor], return_trais set to ``True``"""- if not torch.is_tensor(input):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")-- if len(input.shape) == 2:- input = input.unsqueeze(0)-- if len(input.shape) == 3:- input = input.unsqueeze(0)-- if len(input.shape) != 4:- raise ValueError(f"Input size must have a shape of (*, C, H, W). Got {input.shape}")+ input = _transform_input(input)if not isinstance(return_transform, bool):raise TypeError(f"The return_transform flag must be a bool. Got {type(return_transform)}")@@ -244,17 +235,7 @@ def apply_vflip(input: torch.Tensor, params: Dict[str, torch.Tensor], return_tra"""# TODO: params validation- if not torch.is_tensor(input):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")-- if len(input.shape) == 2:- input = input.unsqueeze(0)-- if len(input.shape) == 3:- input = input.unsqueeze(0)-- if len(input.shape) != 4:- raise ValueError(f"Input size must have a shape of (*, C, H, W). Got {input.shape}")+ input = _transform_input(input)if not isinstance(return_transform, bool):raise TypeError(f"The return_transform flag must be a bool. Got {type(return_transform)}")@@ -304,17 +285,7 @@ def apply_color_jitter(input: torch.Tensor, params: Dict[str, torch.Tensor],"""# TODO: params validation- if not torch.is_tensor(input):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")-- if len(input.shape) == 2:- input = input.unsqueeze(0)-- if len(input.shape) == 3:- input = input.unsqueeze(0)-- if len(input.shape) != 4:- raise ValueError(f"Input size must have a shape of (*, C, H, W). Got {input.shape}")+ input = _transform_input(input)if not isinstance(return_transform, bool):raise TypeError(f"The return_transform flag must be a bool. Got {type(return_transform)}")@@ -359,13 +330,9 @@ def apply_grayscale(input: torch.Tensor, params: Dict[str, torch.Tensor], return"""# TODO: params validation- if not torch.is_tensor(input):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")-- if len(input.shape) == 3 and input.shape[-3] == 3:- input = input.unsqueeze(0)+ input = _transform_input(input)- if len(input.shape) != 4 or input.shape[-3] != 3:+ if _validate_input_shape(input, 2, 3):raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {input.shape}")if not isinstance(return_transform, bool):@@ -394,7 +361,7 @@ def apply_perspective(input: torch.Tensor,r"""Perform perspective transform of the given torch.Tensor or batch of tensors.Args:- input (torch.Tensor): Tensor to be transformed with shape BxCxHxW.+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).start_points (torch.Tensor): Tensor containing [top-left, top-right, bottom-right,bottom-left] of the orignal image with shape Bx4x2.end_points (torch.Tensor): Tensor containing [top-left, top-right, bottom-right,@@ -406,8 +373,7 @@ def apply_perspective(input: torch.Tensor,torch.Tensor: Perspectively transformed tensor."""- if not torch.is_tensor(input):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")+ input = _transform_input(input)device: torch.device = input.devicedtype: torch.dtype = input.dtype@@ -444,7 +410,7 @@ def apply_affine(input: torch.Tensor,return_transform: bool = False) -> UnionType:r"""Random affine transformation of the image keeping center invariantArgs:- input (torch.Tensor): Tensor to be transformed with shape (*, C, H, W).+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).degrees (float or tuple): Range of degrees to select from.If degrees is a number instead of sequence like (min, max), the range of degreeswill be (-degrees, +degrees). Set to 0 to deactivate rotations.@@ -468,8 +434,7 @@ def apply_affine(input: torch.Tensor,'zeros' | 'border' | 'reflection'. Default: 'zeros'."""- if not torch.is_tensor(input):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")+ input = _transform_input(input)device: torch.device = input.devicedtype: torch.dtype = input.dtype@@ -510,6 +475,8 @@ def apply_rotation(input: torch.Tensor, params: Dict[str, torch.Tensor], return_input tensor. If ``False`` and the input is a tuple the applied transformationwont be concatenated"""+ src = params['src'].to(input.device).to(input.dtype)+ dst = params['dst'].to(input.device).to(input.dtype)if not torch.is_tensor(input):raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")@@ -536,3 +503,23 @@ def apply_rotation(input: torch.Tensor, params: Dict[str, torch.Tensor], return_return transformed, trans_matreturn transformed+++def apply_crop(input: torch.Tensor, params: Dict[str, torch.Tensor], return_transform: bool = False) -> UnionType:+ """+ Args:+ params (dict): A dict that must have {'src': torch.Tensor, 'dst': torch.Tensor}. Can be generated from+ kornia.augmentation.param_gen._random_crop_gen+ return_transform (bool): if ``True`` return the matrix describing the transformation applied to each+ input tensor.+ Returns:+ torch.Tensor: The grayscaled input+ torch.Tensor: The applied cropping matrix :math: `(*, 4, 2)` if return_transform flag+ is set to ``True``+ """+ input = _transform_input(input)++ if return_transform:+ return crop_by_boxes(input, params['src'], params['dst'], return_transform=return_transform)++ return crop_by_boxes(input, params['src'], params['dst'], return_transform=return_transform)diff --git a/kornia/augmentation/param_gen.py b/kornia/augmentation/param_gen.pyindex 471146979..4199e3e51 100644--- a/kornia/augmentation/param_gen.py+++ b/kornia/augmentation/param_gen.py@@ -303,3 +303,39 @@ def _get_random_affine_params(transform_h = torch.nn.functional.pad(transform, [0, 0, 0, 1], value=0.)transform_h[..., -1, -1] += 1.0return transform_h+++def _random_crop_gen(batch_size: int, input_size: Tuple[int, int], size: Tuple[int, int],+ resize_to: Optional[Tuple[int, int]] = None) -> Dict[str, torch.Tensor]:+ x_diff = input_size[1] - size[1]+ y_diff = input_size[0] - size[0]++ if x_diff < 0 or y_diff < 0:+ raise ValueError("input_size %s cannot be smaller than crop size %s in any dimension."+ % (str(input_size), str(size)))++ x_start = Uniform(0, x_diff).rsample((batch_size,)).long()+ y_start = Uniform(0, y_diff).rsample((batch_size,)).long()++ crop = torch.tensor([[+ [0, 0],+ [0, size[1]],+ [size[0], 0],+ [size[0], size[1]]+ ]]).repeat(batch_size, 1, 1)++ crop_src = crop.detach()+ crop_src[:, :, 0] += x_start.unsqueeze(dim=0).reshape(batch_size, 1)+ crop_src[:, :, 1] += y_start.unsqueeze(dim=0).reshape(batch_size, 1)++ if resize_to is None:+ crop_dst = crop+ else:+ crop_dst = torch.tensor([[+ [0, 0],+ [0, resize_to[1]],+ [resize_to[0], 0],+ [resize_to[0], resize_to[1]]+ ]]).repeat(batch_size, 1, 1)++ return {'src': crop_src, 'dst': crop_dst}diff --git a/kornia/augmentation/utils.py b/kornia/augmentation/utils.pynew file mode 100644index 000000000..097040ee1--- /dev/null+++ b/kornia/augmentation/utils.py@@ -0,0 +1,41 @@+from typing import Tuple++import torch+++def _transform_input(input: torch.Tensor) -> torch.Tensor:+ r"""Reshape an input tensor to be (*, C, H, W). Accept either (H, W), (C, H, W) or (*, C, H, W).+ Args:+ input: torch.Tensor++ Returns:+ torch.Tensor+ """+ if not torch.is_tensor(input):+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")++ if len(input.shape) not in [2, 3, 4]:+ raise ValueError(+ f"Input size must have a shape of either (H, W), (C, H, W) or (*, C, H, W). Got {input.shape}")++ if len(input.shape) == 2:+ input = input.unsqueeze(0)++ if len(input.shape) == 3:+ input = input.unsqueeze(0)++ return input+++def _validate_input_shape(input: torch.Tensor, channel_index: int, number: int) -> bool:+ r"""Validate if an input has the right shape. e.g. to check if an input is channel first.+ If channel first, the second channel of an RGB input shall be fixed to 3. To verify using:+ _validate_input_shape(input, 2, 3)+ Args:+ input: torch.Tensor+ channel_index: int+ number: int+ Returns:+ bool+ """+ return input.shape[channel_index] == numberdiff --git a/kornia/geometry/transform/crop.py b/kornia/geometry/transform/crop.pyindex c11022d3a..2acd44dd3 100644--- a/kornia/geometry/transform/crop.py+++ b/kornia/geometry/transform/crop.py@@ -8,12 +8,13 @@ from kornia.geometry.transform.imgwarp import (__all__ = ["crop_and_resize",+ "crop_by_boxes","center_crop",]-def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor,- size: Tuple[int, int]) -> torch.Tensor:+def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int, int],+ return_transform: bool = False) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:r"""Extracts crops from the input tensor and resizes them.Args:@@ -64,8 +65,7 @@ def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor,# [x, y] origin# top-left, top-right, bottom-right, bottom-left- points_src: torch.Tensor = boxes.to(- tensor.device).to(tensor.dtype)+ points_src: torch.Tensor = boxes# [x, y] destination# top-left, top-right, bottom-right, bottom-left@@ -74,29 +74,9 @@ def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor,[dst_w - 1, 0],[dst_w - 1, dst_h - 1],[0, dst_h - 1],- ]]).repeat(points_src.shape[0], 1, 1).to(- tensor.device).to(tensor.dtype)+ ]]).repeat(points_src.shape[0], 1, 1)- # warping needs data in the shape of BCHW- is_unbatched: bool = tensor.ndimension() == 3- if is_unbatched:- tensor = torch.unsqueeze(tensor, dim=0)-- # compute transformation between points and warp- dst_trans_src: torch.Tensor = get_perspective_transform(- points_src, points_dst)-- # simulate broadcasting- dst_trans_src = dst_trans_src.expand(tensor.shape[0], -1, -1)-- patches: torch.Tensor = warp_perspective(- tensor, dst_trans_src, (int(dst_h), int(dst_w)))-- # return in the original shape- if is_unbatched:- patches = torch.squeeze(patches, dim=0)-- return patches+ return crop_by_boxes(tensor, points_src, points_dst, return_transform=return_transform)def center_crop(tensor: torch.Tensor, size: Tuple[int, int],@@ -160,7 +140,7 @@ def center_crop(tensor: torch.Tensor, size: Tuple[int, int],[start_y, end_x],[end_y, start_x],[end_y, end_x],- ]]).to(tensor.device).to(tensor.dtype)+ ]])# [y, x] destination# top-left, top-right, bottom-left, bottom-right@@ -169,8 +149,19 @@ def center_crop(tensor: torch.Tensor, size: Tuple[int, int],[0, dst_w - 1],[dst_h - 1, 0],[dst_h - 1, dst_w - 1],- ]]).to(tensor.device).to(tensor.dtype)+ ]])+ return crop_by_boxes(tensor, points_src, points_dst, return_transform=return_transform)+++def crop_by_boxes(tensor, src_box, dst_box,+ return_transform: bool = False) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:+ """A wrapper performs crop transform with bounding boxes.++ """+ print(tensor.ndimension(), tensor.ndimension() in [3, 4])+ if tensor.ndimension() not in [3, 4]:+ raise TypeError("Only tensor with shape (C, H, W) and (B, C, H, W) supported. Got %s" % str(tensor.shape))# warping needs data in the shape of BCHWis_unbatched: bool = tensor.ndimension() == 3if is_unbatched:@@ -178,11 +169,15 @@ def center_crop(tensor: torch.Tensor, size: Tuple[int, int],# compute transformation between points and warpdst_trans_src: torch.Tensor = get_perspective_transform(- points_src, points_dst)- dst_trans_src = dst_trans_src.repeat(tensor.shape[0], 1, 1)+ src_box.to(tensor.device).to(tensor.dtype),+ dst_box.to(tensor.device).to(tensor.dtype)+ )++ # simulate broadcasting+ dst_trans_src = dst_trans_src.expand(tensor.shape[0], -1, -1)patches: torch.Tensor = warp_perspective(- tensor, dst_trans_src, (int(dst_h), int(dst_w)))+ tensor, dst_trans_src, _infer_bounding_box(dst_box))# return in the original shapeif is_unbatched:@@ -192,3 +187,43 @@ def center_crop(tensor: torch.Tensor, size: Tuple[int, int],return patches, dst_trans_srcreturn patches+++def _infer_bounding_box(boxes: torch.Tensor) -> Tuple[int, int]:+ r"""Auto-infer the output sizes.++ Args:+ boxes (torch.Tensor): a tensor containing the coordinates of the+ bounding boxes to be extracted. The tensor must have the shape+ of Bx4x2, where each box is defined in the following (clockwise)+ order: top-left, top-right, bottom-right and bottom-left. The+ coordinates must be in the x, y order.++ Returns:+ torch.Tensor: tensor containing the patches with shape BxN1xN2++ Example:+ >>> boxes = torch.tensor([[+ [1., 1.],+ [1., 2.],+ [2., 1.],+ [2., 2.],+ ]]) # 1x4x2+ >>> _infer_bounding_box(boxes)+ (2, 2)+ """++ assert (boxes[:, 1, 1] - boxes[:, 0, 1] + 1).equal(boxes[:, 3, 1] - boxes[:, 2, 1] + 1), \+ "Boxes must have be square, while get widths %s and %s" % \+ (str(boxes[:, 1, 1] - boxes[:, 0, 1] + 1), str(boxes[:, 3, 1] - boxes[:, 2, 1] + 1))+ assert (boxes[:, 2, 0] - boxes[:, 0, 0]).equal(boxes[:, 3, 0] - boxes[:, 1, 0]), \+ "Boxes must have be square, while get heights %s and %s" % \+ (str(boxes[:, 2, 0] - boxes[:, 0, 0] + 1), str(boxes[:, 3, 0] - boxes[:, 1, 0] + 1))+ assert len((boxes[:, 1, 1] - boxes[:, 0, 1] + 1).unique()) == 1, \+ "Boxes can only have one widths, got %s" % str((boxes[:, 1, 1] - boxes[:, 0, 1] + 1).unique())+ assert len((boxes[:, 2, 0] - boxes[:, 0, 0]).unique()) == 1, \+ "Boxes can only have one heights, got %s" % str((boxes[:, 2, 0] - boxes[:, 0, 0] + 1).unique())++ height = (boxes[:, 2, 0] - boxes[:, 0, 0]).unique().data.item()+ width = (boxes[:, 1, 1] - boxes[:, 0, 1]).unique().data.item()+ return (height, width)