随机旋转是一种图像增强技术,它通过将图像以随机角度进行旋转来增加数据的多样性,从而帮助改善模型的鲁棒性和泛化能力。这在训练深度学习模型时尤其有用,可以使模型更好地适应各种角度的输入。
原图像:
旋转后的图像:
import cv2
import numpy as np
def random_rotate(image, max_angle):
angle = np.random.uniform(-max_angle, max_angle)
height, width = image.shape[:2]
rotation_matrix = cv2.getRotationMatrix2D((width / 2, height / 2), angle, 1)
rotated_image = cv2.warpAffine(image, rotation_matrix, (width, height))
return rotated_image
# 读取图像
image = cv2.imread('input.jpg')
image=cv2.resize(image,(1024,800))
# 随机旋转图像
max_rotation_angle = 30 # 最大旋转角度
rotated_image = random_rotate(image, max_rotation_angle)
# 显示原始图像和旋转后的图像
cv2.imshow('Original Image', image)
cv2.imshow('Rotated Image', rotated_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
随机裁剪是一种常见的数据增强技术,用于增加训练数据的多样性,特别是在处理不同尺寸的图像数据时。
原图像:
随机裁剪后的图像:
import cv2
import numpy as np
def random_crop(image, crop_size):
height, width = image.shape[:2]
crop_height, crop_width = crop_size
if crop_width >= width or crop_height >= height:
raise ValueError("Crop size should be smaller than image size")
x = np.random.randint(0, width - crop_width + 1)
y = np.random.randint(0, height - crop_height + 1)
cropped_image = image[y:y+crop_height, x:x+crop_width]
return cropped_image
# 读取图像
image = cv2.imread('input.jpg')
image=cv2.resize(image,(1024,800))
# 随机裁剪到固定大小
crop_size = (200, 200) # 裁剪尺寸
cropped_image = random_crop(image, crop_size)
# 显示原始图像和裁剪后的图像
cv2.imshow('Original Image', image)
cv2.imshow('Cropped Image', cropped_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
原图像:
亮度调整之后的图像:
def enhance_color(image, alpha, beta):
enhanced_image = cv2.convertScaleAbs(image, alpha=alpha, beta=beta)
return enhanced_image
image = cv2.imread('input.jpg')
color_enhanced_image = enhance_color(image, 1.2, 20)
原图:
亮度、对比度调整后的图像:
import cv2
def adjust_brightness_contrast(image, alpha, beta):
adjusted_image = cv2.convertScaleAbs(image, alpha=alpha, beta=beta)
return adjusted_image
image = cv2.imread('input.jpg')
brightened_image = adjust_brightness_contrast(image, 1.2, 20)
原图:
平滑后的图像:
锐化后的图像:
def apply_image_smoothing(image):
smoothed_image = cv2.GaussianBlur(image, (5, 5), 0)
return smoothed_image
def apply_image_sharpening(image):
kernel = np.array([[-1, -1, -1],
[-1, 9, -1],
[-1, -1, -1]])
sharpened_image = cv2.filter2D(image, -1, kernel)
return sharpened_image
image = cv2.imread('input.jpg')
smoothed_image = apply_image_smoothing(image)
sharpened_image = apply_image_sharpening(image)