π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Optimised clipping in clahe and some other minor optimisations (#1035)
lferraze049b65a1598
diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.pyindex 30c6fb492..fbf175681 100644--- a/kornia/enhance/equalization.py+++ b/kornia/enhance/equalization.py@@ -54,7 +54,7 @@ def _compute_tiles(imgs: torch.Tensor, grid_size: Tuple[int, int], even_tile_siztiles: torch.Tensor = (batch.unfold(1, c, c) # unfold(dimension, size, step).unfold(2, kernel_vert, kernel_vert).unfold(3, kernel_horz, kernel_horz)- .squeeze(1)) # GH x GW x C x TH x TW+ .squeeze(1)).contiguous() # GH x GW x C x TH x TWassert tiles.shape[-5] == grid_size[0] # check the grid sizeassert tiles.shape[-4] == grid_size[1]return tiles, batch@@ -86,13 +86,17 @@ def _compute_interpolation_tiles(padded_imgs: torch.Tensor, tile_size: Tuple[intinterp_tiles: torch.Tensor = (padded_imgs.unfold(1, c, c).unfold(2, interp_kernel_vert, interp_kernel_vert).unfold(3, interp_kernel_horz, interp_kernel_horz)- .squeeze(1)) # 2GH x 2GW x C x TH/2 x TW/2+ .squeeze(1)).contiguous() # 2GH x 2GW x C x TH/2 x TW/2assert interp_tiles.shape[-3] == cassert interp_tiles.shape[-2] == tile_size[0] / 2assert interp_tiles.shape[-1] == tile_size[1] / 2return interp_tiles+def _my_histc(tiles: torch.Tensor, bins: int) -> torch.Tensor:+ return _torch_histc_cast(tiles, bins=bins, min=0, max=1)++def _compute_luts(tiles_x_im: torch.Tensor, num_bins: int = 256, clip: float = 40., diff: bool = False) -> torch.Tensor:r"""Compute luts for a batched set of tiles.@@ -112,36 +116,28 @@ def _compute_luts(tiles_x_im: torch.Tensor, num_bins: int = 256, clip: float = 4b, gh, gw, c, th, tw = tiles_x_im.shapepixels: int = th * tw- tiles: torch.Tensor = tiles_x_im.reshape(-1, pixels) # test with view # T x (THxTW)- histos: torch.Tensor = torch.empty((tiles.shape[0], num_bins), device=tiles.device)+ tiles: torch.Tensor = tiles_x_im.view(-1, pixels) # test with view # T x (THxTW)if not diff:- for i in range(tiles.shape[0]):- histos[i] = _torch_histc_cast(tiles[i], bins=num_bins, min=0, max=1)+ if torch.jit.is_scripting():+ histos = torch.stack([_torch_histc_cast(tile, bins=num_bins, min=0, max=1) for tile in tiles])+ else:+ histos = torch.stack(list(map(_my_histc, tiles, [num_bins] * len(tiles))))else:bins: torch.Tensor = torch.linspace(0, 1, num_bins, device=tiles.device)histos = histogram(tiles, bins, torch.tensor(0.001)).squeeze()histos *= pixels- # clip limit (TODO: optimice the code)if clip > 0.:- clip_limit: torch.Tensor = torch.tensor(- max(clip * pixels // num_bins, 1), dtype=histos.dtype, device=tiles.device)-- clip_idxs: torch.Tensor = histos > clip_limit- for i in range(histos.shape[0]):- hist: torch.Tensor = histos[i]- idxs = clip_idxs[i]- if idxs.any():- clipped: float = float((hist[idxs] - clip_limit).sum().item())- hist = torch.where(idxs, clip_limit, hist)-- redist: float = clipped // num_bins- hist += redist-- residual: float = clipped - redist * num_bins- if residual:- hist[0:int(residual)] += 1- histos[i] = hist+ max_val: float = max(clip * pixels // num_bins, 1)+ histos.clamp_(max=max_val)+ clipped: torch.Tensor = pixels - histos.sum(1)+ redist: torch.Tensor = clipped // num_bins+ histos += redist[None].transpose(0, 1)+ residual: torch.Tensor = clipped - redist * num_bins+ # trick to avoid using a loop to assign the residual+ v_range: torch.Tensor = torch.arange(num_bins, device=histos.device)+ mat_range: torch.Tensor = v_range.repeat(histos.shape[0], 1)+ histos += mat_range < residual[None].transpose(0, 1)lut_scale: float = (num_bins - 1) / pixelsluts: torch.Tensor = torch.cumsum(histos, 1) * lut_scale@@ -169,20 +165,23 @@ def _map_luts(interp_tiles: torch.Tensor, luts: torch.Tensor) -> torch.Tensor:num_imgs, gh, gw, c, th, tw = interp_tiles.shape# precompute idxs for non corner regions (doing it in cpu seems sligthly faster)- j_idxs = torch.ones(gh - 2, 4, dtype=torch.long) * torch.arange(1, gh - 1).reshape(gh - 2, 1)- i_idxs = torch.ones(gw - 2, 4, dtype=torch.long) * torch.arange(1, gw - 1).reshape(gw - 2, 1)- j_idxs = j_idxs // 2 + j_idxs % 2- j_idxs[:, 0:2] -= 1- i_idxs = i_idxs // 2 + i_idxs % 2- # i_idxs[:, [0, 2]] -= 1 # this slicing is not supported by jit- i_idxs[:, 0] -= 1- i_idxs[:, 2] -= 1+ j_idxs = torch.empty(0, 4, dtype=torch.long)+ if gh > 2:+ j_floor = torch.arange(1, gh - 1).view(gh - 2, 1) // 2+ j_idxs = torch.tensor([[0, 0, 1, 1], [-1, -1, 0, 0]] * ((gh - 2) // 2)) # reminder + j_idxs[:, 0:2] -= 1+ j_idxs += j_floor++ i_idxs = torch.empty(0, 4, dtype=torch.long)+ if gw > 2:+ i_floor = torch.arange(1, gw - 1).view(gw - 2, 1) // 2+ i_idxs = torch.tensor([[0, 1, 0, 1], [-1, 0, -1, 0]] * ((gw - 2) // 2)) # reminder + i_idxs[:, [0, 2]] -= 1+ i_idxs += i_floor# selection of luts to interpolate each patch# create a tensor with dims: interp_patches height and width x 4 x num channels x bins in the histograms# the tensor is init to -1 to denote non init hists- luts_x_interp_tiles: torch.Tensor = -torch.ones(- num_imgs, gh, gw, 4, c, luts.shape[-1], device=interp_tiles.device) # B x GH x GW x 4 x C x 256+ luts_x_interp_tiles: torch.Tensor = torch.full( # B x GH x GW x 4 x C x 256+ (num_imgs, gh, gw, 4, c, luts.shape[-1]), -1, dtype=interp_tiles.dtype, device=interp_tiles.device)# corner regionsluts_x_interp_tiles[:, 0::gh - 1, 0::gw - 1, 0] = luts[:, 0::max(gh // 2 - 1, 1), 0::max(gw // 2 - 1, 1)]# border region (h)@@ -222,17 +221,18 @@ def _compute_equalized_tiles(interp_tiles: torch.Tensor, luts: torch.Tensor) -># equalize tilesflatten_interp_tiles: torch.Tensor = (interp_tiles * 255).long().flatten(-2, -1) # B x GH x GW x 4 x C x (THxTW)flatten_interp_tiles = flatten_interp_tiles.unsqueeze(-3).expand(num_imgs, gh, gw, 4, c, th * tw)- preinterp_tiles_equalized = torch.gather(- mapped_luts, 5, flatten_interp_tiles).reshape(num_imgs, gh, gw, 4, c, th, tw) # B x GH x GW x 4 x C x TH x TW+ preinterp_tiles_equalized = torch.gather( # B x GH x GW x 4 x C x TH x TW+ mapped_luts, 5, flatten_interp_tiles).to(interp_tiles).reshape(num_imgs, gh, gw, 4, c, th, tw)# interp tiles- tiles_equalized: torch.Tensor = torch.zeros_like(interp_tiles, dtype=torch.long)+ tiles_equalized: torch.Tensor = torch.zeros_like(interp_tiles)# compute the interpolation weights (shapes are 2 x TH x TW because they must be applied to 2 interp tiles)- ih = torch.arange(2 * th - 1, -1, -1, device=interp_tiles.device).div(+ ih = torch.arange(2 * th - 1, -1, -1, dtype=interp_tiles.dtype, device=interp_tiles.device).div(2. * th - 1)[None].transpose(-2, -1).expand(2 * th, tw)ih = ih.unfold(0, th, th).unfold(1, tw, tw) # 2 x 1 x TH x TW- iw = torch.arange(2 * tw - 1, -1, -1, device=interp_tiles.device).div(2. * tw - 1).expand(th, 2 * tw)+ iw = torch.arange(2 * tw - 1, -1, -1, dtype=interp_tiles.dtype, device=interp_tiles.device).div(+ 2. * tw - 1).expand(th, 2 * tw)iw = iw.unfold(0, th, th).unfold(1, tw, tw) # 1 x 2 x TH x TW# compute row and column interpolation weigths@@ -241,27 +241,27 @@ def _compute_equalized_tiles(interp_tiles: torch.Tensor, luts: torch.Tensor) -># internal regionstl, tr, bl, br = preinterp_tiles_equalized[:, 1:-1, 1:-1].unbind(3)- t = tiw * (tl - tr) + tr- b = tiw * (bl - br) + br- tiles_equalized[:, 1:-1, 1:-1] = tih * (t - b) + b+ t = torch.addcmul(tr, tiw, torch.sub(tl, tr))+ b = torch.addcmul(br, tiw, torch.sub(bl, br))+ tiles_equalized[:, 1:-1, 1:-1] = torch.addcmul(b, tih, torch.sub(t, b))# corner regionstiles_equalized[:, 0::gh - 1, 0::gw - 1] = preinterp_tiles_equalized[:, 0::gh - 1, 0::gw - 1, 0]# border region (h)t, b, _, _ = preinterp_tiles_equalized[:, 1:-1, 0].unbind(2)- tiles_equalized[:, 1:-1, 0] = tih.squeeze(1) * (t - b) + b+ tiles_equalized[:, 1:-1, 0] = torch.addcmul(b, tih.squeeze(1), torch.sub(t, b))t, b, _, _ = preinterp_tiles_equalized[:, 1:-1, gh - 1].unbind(2)- tiles_equalized[:, 1:-1, gh - 1] = tih.squeeze(1) * (t - b) + b+ tiles_equalized[:, 1:-1, gh - 1] = torch.addcmul(b, tih.squeeze(1), torch.sub(t, b))# border region (w)l, r, _, _ = preinterp_tiles_equalized[:, 0, 1:-1].unbind(2)- tiles_equalized[:, 0, 1:-1] = tiw * (l - r) + r+ tiles_equalized[:, 0, 1:-1] = torch.addcmul(r, tiw, torch.sub(l, r))l, r, _, _ = preinterp_tiles_equalized[:, gw - 1, 1:-1].unbind(2)- tiles_equalized[:, gw - 1, 1:-1] = tiw * (l - r) + r+ tiles_equalized[:, gw - 1, 1:-1] = torch.addcmul(r, tiw, torch.sub(l, r))# same type as the input- return tiles_equalized.to(interp_tiles).div(255.)+ return tiles_equalized.div(255.)def equalize_clahe(input: torch.Tensor, clip_limit: float = 40., grid_size: Tuple[int, int] = (8, 8)) -> torch.Tensor:@@ -327,8 +327,8 @@ def equalize_clahe(input: torch.Tensor, clip_limit: float = 40., grid_size: Tuplequalized_tiles: torch.Tensor = _compute_equalized_tiles(interp_tiles, luts) # B x 2GH x 2GW x C x TH/2 x TW/2# reconstruct the images form the tiles- eq_imgs: torch.Tensor = torch.cat(equalized_tiles.unbind(2), 4)- eq_imgs = torch.cat(eq_imgs.unbind(1), 2)+# try permute + contiguous + view+ eq_imgs: torch.Tensor = equalized_tiles.permute(0, 3, 1, 4, 2, 5).reshape_as(img_padded)h, w = imgs.shape[-2:]eq_imgs = eq_imgs[..., :h, :w] # crop imgs if they were paddeddiff --git a/test/enhance/test_equalization.py b/test/enhance/test_equalization.pyindex fd0beae44..90a20fb06 100644--- a/test/enhance/test_equalization.py+++ b/test/enhance/test_equalization.py@@ -111,8 +111,8 @@ class TestEqualization(BaseTester):# NOTE: for next versions we need to improve the computation of the LUT# and test with a better imageassert torch.allclose(res[..., 0, :], torch.tensor(- [[[0.2471, 0.4980, 0.7490, 0.6667, 0.4980, 0.4980, 0.7490, 0.4980,- 0.4980, 0.2471, 0.7490, 0.4980, 0.4980, 0.2471, 0.4980, 0.4980,+ [[[0.2471, 0.4980, 0.7490, 0.6667, 0.4980, 0.4980, 0.7490, 0.4993,+ 0.4980, 0.2471, 0.7490, 0.4993, 0.4980, 0.2471, 0.4980, 0.4993,0.3333, 0.2471, 0.4980, 1.0000]]], dtype=res.dtype, device=res.device), atol=1e-04, rtol=1e-04)def test_clahe(self, img):@@ -122,6 +122,6 @@ class TestEqualization(BaseTester):# NOTE: for next versions we need to improve the computation of the LUT# and test with a better imageassert torch.allclose(res[..., 0, :], torch.tensor(- [[[0.1216, 0.8745, 0.9373, 0.9137, 0.8745, 0.8745, 0.9373, 0.8745,+ [[[0.1216, 0.8745, 0.9373, 0.9163, 0.8745, 0.8745, 0.9373, 0.8745,0.8745, 0.8118, 0.9373, 0.8745, 0.8745, 0.8118, 0.8745, 0.8745,- 0.8314, 0.8118, 0.8745, 1.0000]]], dtype=res.dtype, device=res.device), atol=1e-04, rtol=1e-04)+ 0.8327, 0.8118, 0.8745, 1.0000]]], dtype=res.dtype, device=res.device), atol=1e-04, rtol=1e-04)