隨機旋轉
隨機旋轉是一種圖像增強技術,它通過將圖像以隨機角度進行旋轉來增加數據的多樣性,從而幫助改善模型的魯棒性和泛化能力。這在訓練深度學習模型時尤其有用,可以使模型更好地適應各種角度的輸入。
原圖像:
旋轉后的圖像:
?代碼實現:
import cv2import numpy as npdef 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_sizeif 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_imageimage = cv2.imread('input.jpg')
color_enhanced_image = enhance_color(image, 1.2, 20)
亮度和對比度調整:
- 亮度調整:改變圖像的亮度水平,使圖像變得更亮或更暗。
- 對比度調整:調整圖像中像素值的范圍,以擴展或縮小亮度差異,使圖像更具視覺對比度。
原圖:
?
?亮度、對比度調整后的圖像:
代碼實現:
import cv2def adjust_brightness_contrast(image, alpha, beta):adjusted_image = cv2.convertScaleAbs(image, alpha=alpha, beta=beta)return adjusted_imageimage = 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_imagedef 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_imageimage = cv2.imread('input.jpg')
smoothed_image = apply_image_smoothing(image)
sharpened_image = apply_image_sharpening(image)