python實現(xiàn)圖像的隨機增強變換
從文件夾中隨機選擇一定數(shù)量的圖像,然后對每個選定的圖像進行一次隨機的數(shù)據(jù)增強變換。
import os
import random
import cv2
import numpy as np
from PIL import Image, ImageEnhance, ImageOps
# 定義各種數(shù)據(jù)增強方法
def random_rotate(image, angle_range=(-30, 30)):
angle = random.uniform(angle_range[0], angle_range[1])
(h, w) = image.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(image, M, (w, h), borderMode=cv2.BORDER_REFLECT)
return rotated
def random_translate(image, translate_range=(-50, 50)):
tx = random.randint(translate_range[0], translate_range[1])
ty = random.randint(translate_range[0], translate_range[1])
(h, w) = image.shape[:2]
M = np.float32([[1, 0, tx], [0, 1, ty]])
translated = cv2.warpAffine(image, M, (w, h), borderMode=cv2.BORDER_REFLECT)
return translated
def random_flip(image):
flip_code = random.choice([-1, 0, 1])
flipped = cv2.flip(image, flip_code)
return flipped
def random_scale(image, scale_range=(0.8, 1.2)):
scale = random.uniform(scale_range[0], scale_range[1])
(h, w) = image.shape[:2]
new_dim = (int(w * scale), int(h * scale))
scaled = cv2.resize(image, new_dim, interpolation=cv2.INTER_LINEAR)
return scaled
def random_crop(image, crop_size=(224, 224)):
(h, w) = image.shape[:2]
if crop_size[0] > h or crop_size[1] > w:
# 當(dāng)裁剪尺寸大于圖像尺寸時,拋出異?;蛘{(diào)整裁剪尺寸
raise ValueError("Crop size is larger than image size.")
top = random.randint(0, h - crop_size[0])
left = random.randint(0, w - crop_size[1])
cropped = image[top:top+crop_size[0], left:left+crop_size[1]]
return cropped
def random_color_jitter(image):
pil_image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
color_jitter = ImageEnhance.Color(pil_image).enhance(random.uniform(0.6, 1.4))
contrast_jitter = ImageEnhance.Contrast(color_jitter).enhance(random.uniform(0.5, 1.5))
brightness_jitter = ImageEnhance.Brightness(contrast_jitter).enhance(random.uniform(0.6, 1.4))
sharpness_jitter = ImageEnhance.Sharpness(brightness_jitter).enhance(random.uniform(0.6, 1.4))
jittered = cv2.cvtColor(np.array(sharpness_jitter), cv2.COLOR_RGB2BGR)
return jittered
def random_add_noise(image):
row, col, ch = image.shape
mean = 0
var = 0.1
sigma = var ** 0.5
gauss = np.random.normal(mean, sigma, (row, col, ch))
gauss = gauss.reshape(row, col, ch)
noisy = image + gauss
return np.clip(noisy, 0, 255).astype(np.uint8)
# 數(shù)據(jù)增強主函數(shù)
def augment_random_images(src_folder, dst_folder, num_images_to_select, num_augmentations_per_image):
if not os.path.exists(dst_folder):
os.makedirs(dst_folder)
# 獲取所有圖像文件名
all_filenames = [f for f in os.listdir(src_folder) if f.lower().endswith(('.png', '.jpg', '.jpeg'))]
# 如果選擇的圖像數(shù)量大于總圖像數(shù)量,則只處理全部圖像
num_images_to_process = min(num_images_to_select, len(all_filenames))
# 隨機選擇圖像
selected_filenames = random.sample(all_filenames, num_images_to_process)
# 創(chuàng)建一個增強方法列表
augmentation_methods = [
random_rotate,
#random_translate,
random_flip,
random_scale,
#random_crop,
random_color_jitter,
random_add_noise
]
for filename in selected_filenames:
img_path = os.path.join(src_folder, filename)
image = cv2.imread(img_path)
for i in range(num_augmentations_per_image):
# 隨機選擇一種增強方法
augmentation_method = random.choice(augmentation_methods)
# 應(yīng)用選中的增強方法
augmented_img = augmentation_method(image)
# 保存增強后的圖像
base_name, ext = os.path.splitext(filename)
save_path = os.path.join(dst_folder, f"{base_name}_aug_{i}{ext}")
cv2.imwrite(save_path, augmented_img)
if __name__ == "__main__":
src_folder = 'path/to/source/folder' # 替換為你的源文件夾路徑
dst_folder = 'path/to/destination/folder' # 替換為你要保存增強圖像的文件夾路徑
num_images_to_select = 10 # 從源文件夾中隨機選擇的圖像數(shù)量
num_augmentations_per_image = 5 # 每張圖像生成的增強圖像數(shù)量
augment_random_images(src_folder, dst_folder, num_images_to_select, num_augmentations_per_image)
print(f"圖像增強完成,增強后的圖像已保存到 {dst_folder}")說明
- 隨機選擇圖像:從源文件夾中隨機選擇num_images_to_select數(shù)量的圖像。
- 隨機選擇一種增強方法:對于每張選定的圖像,隨機選擇一種數(shù)據(jù)增強方法。
- 應(yīng)用增強方法:對每張選定的圖像應(yīng)用所選的增強方法。
- 保存增強后的圖像:將增強后的圖像保存到目標(biāo)文件夾中。
參數(shù)
•src_folder:源文件夾路徑。
•dst_folder:目標(biāo)文件夾路徑。
•num_images_to_select:從源文件夾中隨機選擇的圖像數(shù)量。
•num_augmentations_per_image:每張選定的圖像生成的增強圖像數(shù)量。
請確保將src_folder和dst_folder變量設(shè)置為您實際使用的文件夾路徑,并根據(jù)需要調(diào)整num_images_to_select和num_augmentations_per_image的值。運行這段代碼后,將得到從源文件夾中隨機選擇的圖像,并對這些圖像進行了隨機的數(shù)據(jù)增強變換。
到此這篇關(guān)于python實現(xiàn)圖像的隨機增強變換的文章就介紹到這了,更多相關(guān)python圖像隨機增強內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于Python中異常(Exception)的匯總
異常是指程序中的例外,違例情況。異常機制是指程序出現(xiàn)錯誤后,程序的處理方法。當(dāng)出現(xiàn)錯誤后,程序的執(zhí)行流程發(fā)生改變,程序的控制權(quán)轉(zhuǎn)移到異常處理。下面這篇文章主要匯總了關(guān)于Python中異常(Exception)的相關(guān)資料,需要的朋友可以參考下。2017-01-01
Python?ArcPy實現(xiàn)批量對大量遙感影像相減做差
這篇文章主要為大家介紹了如何基于Python中ArcPy模塊實現(xiàn)對大量柵格遙感影像文件批量進行相減做差,文中的示例代碼講解詳細(xì),感興趣的可以了解一下2023-06-06
Python爬取門戶論壇評論淺談Python未來發(fā)展方向
這篇文章主要介紹了如何實現(xiàn)Python爬取門戶論壇評論,附含圖片示例代碼,講解了詳細(xì)的操作過程,有需要的的朋友可以借鑒參考下,希望可以有所幫助2021-09-09
詳解python函數(shù)的閉包問題(內(nèi)部函數(shù)與外部函數(shù)詳述)
這篇文章主要介紹了python函數(shù)的閉包問題,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05

