%%capture
!pip install kornia
!pip install kornia-rs
Image patch generation
Intermediate
Patches
kornia.geometry
In this tutorial we are going to learn how to generate image patches using
kornia.geometry
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/homography/img1.ppm") download_image(
'img1.ppm'
First load libraries and images
%matplotlib inline
import kornia as K
import matplotlib.pyplot as plt
import torch
def imshow(image: torch.tensor, height: int = 10, width: int = 10):
"""Utility function to plot images."""
=(height, width))
plt.figure(figsize
plt.imshow(K.tensor_to_image(image))"off")
plt.axis( plt.show()
Load and show the original image
0)
torch.manual_seed(
= K.io.load_image("img1.ppm", K.io.ImageLoadType.RGB32)[None, ...] # BxCxHxW
timg: torch.Tensor
10, 10) imshow(timg,
In the following section we are going to take the original image and generate random crops of a given size.
= K.augmentation.RandomCrop((64, 64))
random_crop
= torch.cat([random_crop(timg) for _ in range(15)], dim=-1)
patch
0], 22, 22) imshow(patch[
Next, we will show how to crop patches and apply forth and back random geometric transformations.
# transform a patch
= K.augmentation.RandomCrop((64, 64))
random_crop = K.augmentation.RandomAffine([-15, 15], [0.0, 0.25])
random_affine
# crop
= random_crop(timg)
patch
# transform and retrieve transformation
= random_affine(patch)
patch_affine = random_affine.get_transformation_matrix(patch)
transformation
# invert patch
= patch.shape
_, _, H, W = K.geometry.warp_perspective(patch_affine, torch.inverse(transformation), (H, W))
patch_inv
# visualise - (original, transformed, reconstructed)
= torch.cat([patch, patch_affine, patch_inv], dim=-1)
patches_vis 15, 15) imshow(patches_vis,