%%capture
!pip install kornia
!pip install kornia-rs
Edge Detection
Basic
Edge Detection
kornia.filters
In this tutorial we are going to learn how to detect edges in images with
kornia.filters
components.
import io
import requests
def download_image(url: str, filename: str = "") -> str:
= url.split("/")[-1] if len(filename) == 0 else filename
filename # Download
= io.BytesIO(requests.get(url).content)
bytesio # Save file
with open(filename, "wb") as outfile:
outfile.write(bytesio.getbuffer())
return filename
= "https://github.com/kornia/data/raw/main/doraemon.png"
url download_image(url)
'doraemon.png'
import cv2
import kornia as K
import numpy as np
import torch
import torchvision
from matplotlib import pyplot as plt
We use Kornia to load an image to memory represented in a torch.tensor
= K.io.load_image("doraemon.png", K.io.ImageLoadType.RGB32)[None, ...] # BxCxHxW
x_rgb: torch.Tensor
= K.color.rgb_to_grayscale(x_rgb) x_gray
def imshow(input: torch.Tensor):
= torchvision.utils.make_grid(input, nrow=2, padding=5)
out = K.utils.tensor_to_image(out)
out_np: np.ndarray
plt.imshow(out_np)"off")
plt.axis( plt.show()
imshow(x_gray)
1st order derivates
= K.filters.spatial_gradient(x_gray, order=1) # BxCx2xHxW
grads: torch.Tensor = grads[:, :, 0]
grads_x = grads[:, :, 1] grads_y
# Show first derivatives in x
1.0 - grads_x.clamp(0.0, 1.0)) imshow(
# Show first derivatives in y
1.0 - grads_y.clamp(0.0, 1.0)) imshow(
2nd order derivatives
= K.filters.spatial_gradient(x_gray, order=2) # BxCx2xHxW
grads: torch.Tensor = grads[:, :, 0]
grads_x = grads[:, :, 1] grads_y
# Show second derivatives in x
1.0 - grads_x.clamp(0.0, 1.0)) imshow(
# Show second derivatives in y
1.0 - grads_y.clamp(0.0, 1.0)) imshow(
Sobel Edges
Once with the gradients in the two directions we can computet the Sobel edges. However, in kornia we already have it implemented.
= K.filters.sobel(x_gray)
x_sobel: torch.Tensor 1.0 - x_sobel) imshow(
Laplacian edges
= K.filters.laplacian(x_gray, kernel_size=5)
x_laplacian: torch.Tensor 1.0 - x_laplacian.clamp(0.0, 1.0)) imshow(
Canny edges
= K.filters.canny(x_gray)[0]
x_laplacian: torch.Tensor 1.0 - x_laplacian.clamp(0.0, 1.0)) imshow(