Image enhancement using torchvision’s transforms
import torch
from torchvision import transforms
import numpy as np
import PIL.Image as Image
import matplotlib.pyplot as plt
def imshow(img_path, transform):
img = Image.open(img_path)
fig,ax = plt.subplots(1, 2, figsize=(15, 4))
ax[0].set_title(f'Original image {img.size}')
ax[0].imshow(img)
img = transform(img)
ax[1].set_title(f'Transformed image {img.size}')
ax[1].imshow(img)
path="D:/Desktop/lenna.png"
Resize Rescale
#此函数用于将图像的高度和宽度调整为我们想要的特定大小。
tranform = transforms.Resize((224, 224))
imshow(path,tranform)
Cropping
#使用 CenterCrop 来返回一个中心裁剪的图像。
tranform = transforms.CenterCrop((224, 224))
imshow(path,tranform)
RandomResizedCrop
#Crop and resize.
tranform = transforms.RandomResizedCrop((100, 300))
imshow(path,tranform)
Flipping
#Flip the image horizontally or vertically
transform = transforms.RandomHorizontalFlip()
imshow(path,tranform)
Padding
#Pad transform by the specified amount on all edges of the image
= transforms.Pad((50,50,50,50))
imshow(path,tranform)
Rotation
#The image randomly applies a rotation angle
transform = transforms.RandomRotation(45)
imshow(path,tranform)
Random Affine
#Keep the center constant transform
transform = transforms.RandomAffine(1, translate=(0.5, 0.5), scale=(1, 1), shear=(1,1), fillcolor=(256,256,256)) imshow(path,
tranform )
Gaussian Blur
#The image will be blurred using Gaussian blur.
transform = transforms.GaussianBlur(7, 3)
imshow(path, transform)
Grayscale
transform = transforms.Grayscale(num_output_channels=3)
imshow(path, transform)
Brightness
#Change the brightness of the image The resulting image becomes darker or lighter when compared to the original image.
transform = transforms.ColorJitter(brightness=2)
imshow(path, transform)
Contrast
#The degree of difference between the darkest and lightest parts of an image is called contrast. The contrast of the image can also be adjusted as an enhancement.
transform = transforms.ColorJitter(contrast=2)
imshow(path, transform)
Saturation
#Saturation
transformr=transforms.ColorJitter(saturation=20)
imshow(path, transform)
Hue
#Hue is defined as the shade of a color in an image.
tranformr=transforms.ColorJitter(hue=2)
imshow(path, transform)