欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python實現(xiàn)圖像的隨機(jī)增強(qiáng)變換

 更新時間:2024年11月12日 15:14:59   作者:Ysn0719  
這篇文章主要為大家介紹了如何利用pythons制作一個小工具工具,可以實現(xiàn)圖像的隨機(jī)增強(qiáng)變換,可用于分類訓(xùn)練數(shù)據(jù)的增強(qiáng),有需要的可以參考下

從文件夾中隨機(jī)選擇一定數(shù)量的圖像,然后對每個選定的圖像進(jìn)行一次隨機(jī)的數(shù)據(jù)增強(qiáng)變換。

import os
import random
import cv2
import numpy as np
from PIL import Image, ImageEnhance, ImageOps

# 定義各種數(shù)據(jù)增強(qiáng)方法
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ù)增強(qiáng)主函數(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))

    # 隨機(jī)選擇圖像
    selected_filenames = random.sample(all_filenames, num_images_to_process)

    # 創(chuàng)建一個增強(qiá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):
            # 隨機(jī)選擇一種增強(qiáng)方法
            augmentation_method = random.choice(augmentation_methods)
            
            # 應(yīng)用選中的增強(qiáng)方法
            augmented_img = augmentation_method(image)

            # 保存增強(qiáng)后的圖像
            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'  # 替換為你要保存增強(qiáng)圖像的文件夾路徑
    num_images_to_select = 10  # 從源文件夾中隨機(jī)選擇的圖像數(shù)量
    num_augmentations_per_image = 5  # 每張圖像生成的增強(qiáng)圖像數(shù)量

    augment_random_images(src_folder, dst_folder, num_images_to_select, num_augmentations_per_image)
    print(f"圖像增強(qiáng)完成,增強(qiáng)后的圖像已保存到 {dst_folder}")

說明

  • 隨機(jī)選擇圖像:從源文件夾中隨機(jī)選擇num_images_to_select數(shù)量的圖像。
  • 隨機(jī)選擇一種增強(qiáng)方法:對于每張選定的圖像,隨機(jī)選擇一種數(shù)據(jù)增強(qiáng)方法。
  • 應(yīng)用增強(qiáng)方法:對每張選定的圖像應(yīng)用所選的增強(qiáng)方法。
  • 保存增強(qiáng)后的圖像:將增強(qiáng)后的圖像保存到目標(biāo)文件夾中。

參數(shù)

•src_folder:源文件夾路徑。

•dst_folder:目標(biāo)文件夾路徑。

•num_images_to_select:從源文件夾中隨機(jī)選擇的圖像數(shù)量。

•num_augmentations_per_image:每張選定的圖像生成的增強(qiáng)圖像數(shù)量。

請確保將src_folder和dst_folder變量設(shè)置為您實際使用的文件夾路徑,并根據(jù)需要調(diào)整num_images_to_select和num_augmentations_per_image的值。運(yùn)行這段代碼后,將得到從源文件夾中隨機(jī)選擇的圖像,并對這些圖像進(jìn)行了隨機(jī)的數(shù)據(jù)增強(qiáng)變換。

到此這篇關(guān)于python實現(xiàn)圖像的隨機(jī)增強(qiáng)變換的文章就介紹到這了,更多相關(guān)python圖像隨機(jī)增強(qiáng)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 關(guān)于Python中異常(Exception)的匯總

    關(guān)于Python中異常(Exception)的匯總

    異常是指程序中的例外,違例情況。異常機(jī)制是指程序出現(xiàn)錯誤后,程序的處理方法。當(dāng)出現(xiàn)錯誤后,程序的執(zhí)行流程發(fā)生改變,程序的控制權(quán)轉(zhuǎn)移到異常處理。下面這篇文章主要匯總了關(guān)于Python中異常(Exception)的相關(guān)資料,需要的朋友可以參考下。
    2017-01-01
  • python查看微信好友是否刪除自己

    python查看微信好友是否刪除自己

    這篇文章主要為大家詳細(xì)介紹了python查看微信好友是否刪除自己,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-12-12
  • Python中OTSU算法的原理與實現(xiàn)詳解

    Python中OTSU算法的原理與實現(xiàn)詳解

    OTSU算法是大津展之提出的閾值分割方法,又叫最大類間方差法,本文主要為大家詳細(xì)介紹了OTSU算法的原理與Python實現(xiàn),感興趣的小伙伴可以了解下
    2023-12-12
  • Python?ArcPy實現(xiàn)批量對大量遙感影像相減做差

    Python?ArcPy實現(xiàn)批量對大量遙感影像相減做差

    這篇文章主要為大家介紹了如何基于Python中ArcPy模塊實現(xiàn)對大量柵格遙感影像文件批量進(jìn)行相減做差,文中的示例代碼講解詳細(xì),感興趣的可以了解一下
    2023-06-06
  • Python爬取門戶論壇評論淺談Python未來發(fā)展方向

    Python爬取門戶論壇評論淺談Python未來發(fā)展方向

    這篇文章主要介紹了如何實現(xiàn)Python爬取門戶論壇評論,附含圖片示例代碼,講解了詳細(xì)的操作過程,有需要的的朋友可以借鑒參考下,希望可以有所幫助
    2021-09-09
  • Python?tuple方法和string常量介紹

    Python?tuple方法和string常量介紹

    這篇文章主要介紹了Python?tuple方法和string常量,文章基于python的相關(guān)資料展開詳細(xì)內(nèi)容,對初學(xué)python的通知有一定的參考價值,需要的小伙伴可以參考一下
    2022-05-05
  • keras回調(diào)函數(shù)的使用

    keras回調(diào)函數(shù)的使用

    本文主要介紹了keras回調(diào)函數(shù)的使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03
  • 基于Python實現(xiàn)IP代理池

    基于Python實現(xiàn)IP代理池

    在網(wǎng)絡(luò)爬蟲或數(shù)據(jù)采集領(lǐng)域,IP代理池是一種常用的工具,本文將詳細(xì)介紹如何使用Python實現(xiàn)一個簡單的IP代理池,有需要的可以參考一下
    2024-11-11
  • Python畫圖常用命令大全(詳解)

    Python畫圖常用命令大全(詳解)

    這篇文章主要介紹了Python畫圖常用命令大全,內(nèi)容包括,matplotlib庫默認(rèn)英文字體,讀取exal方法,論文圖片的類型和格式,柱狀圖擴(kuò)展等知識,需要的朋友可以參考下
    2021-09-09
  • 詳解python函數(shù)的閉包問題(內(nèi)部函數(shù)與外部函數(shù)詳述)

    詳解python函數(shù)的閉包問題(內(nèi)部函數(shù)與外部函數(shù)詳述)

    這篇文章主要介紹了python函數(shù)的閉包問題,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-05-05

最新評論