Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_jit(self, device):
@torch.jit.script
def op_script(input):
return kornia.filters.sobel(input)
img = torch.rand(2, 3, 4, 5).to(device)
actual = op_script(img)
expected = kornia.filters.sobel(img)
assert_allclose(actual, expected)
def test_jit(self, device):
@torch.jit.script
def op_script(
input: torch.Tensor,
ksize: int,
angle: float,
direction: float
) -> torch.Tensor:
return kornia.filters.motion_blur(input, ksize, angle, direction)
img = torch.rand(2, 3, 4, 5).to(device)
ksize = 5
angle = 65.
direction = .1
actual = op_script(img, ksize, angle, direction)
expected = kornia.filters.motion_blur(img, ksize, angle, direction)
assert_allclose(actual, expected)
def test_gradcheck(self, device):
batch_size, channels, depth, height, width = 1, 2, 3, 5, 4
img = torch.rand(batch_size, channels, depth, height, width).to(device)
img = utils.tensor_to_gradcheck_var(img) # to var
assert gradcheck(kornia.filters.spatial_gradient3d, (img,),
raise_exception=True)
def test_shape_batch(self, device):
inp = torch.zeros(3, 2, 4, 4).to(device)
sobel = kornia.filters.Sobel()
assert sobel(inp).shape == (3, 2, 4, 4)
def test_laplacian(self, batch_shape, device):
kernel_size = 5
input = torch.rand(batch_shape).to(device)
laplace = kornia.filters.Laplacian(kernel_size)
assert laplace(input).shape == batch_shape
def op_script(input: torch.Tensor,
kernel_size: Tuple[int, int]) -> torch.Tensor:
return kornia.filters.median_blur(input, kernel_size)
kernel_size = (3, 5)
expected = torch.tensor([[[[
[0., 1., 0., -1., 0.],
[1., 3., 0., -3., -1.],
[2., 4., 0., -4., -2.],
[1., 3., 0., -3., -1.],
[0., 1., 0., -1., 0.],
], [
[0., 1., 2., 1., 0.],
[1., 3., 4., 3., 1.],
[0., 0., 0., 0., 0],
[-1., -3., -4., -3., -1],
[0., -1., -2., -1., 0.],
]]]]).to(device)
edges = kornia.filters.spatial_gradient(inp, normalized=False)
assert_allclose(edges, expected)
def op_script(input):
return kornia.filters.spatial_gradient(input)
img = torch.rand(2, 3, 4, 5).to(device)
import torch
import kornia
import cv2
import numpy as np
import matplotlib.pyplot as plt
# read the image with OpenCV
img: np.ndarray = cv2.imread('./data/lena.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# convert to torch tensor
data: torch.tensor = kornia.image_to_tensor(img, keepdim=False) # BxCxHxW
# create the operator
gauss = kornia.filters.GaussianBlur2d((11, 11), (10.5, 10.5))
# blur the image
x_blur: torch.tensor = gauss(data.float())
# convert back to numpy
img_blur: np.ndarray = kornia.tensor_to_image(x_blur.byte())
# Create the plot
fig, axs = plt.subplots(1, 2, figsize=(16, 10))
axs = axs.ravel()
axs[0].axis('off')
axs[0].set_title('image source')
axs[0].imshow(img)
axs[1].axis('off')