# 不增广标签的图像增广
# 增广后和增广前的图像放在一个文件夹里
import os
import random
import numpy as np
from PIL import Image
# Set hyperparameters
alpha = 2.0
crop_size = 512
# Load images from folder
data_dir = 'origin_images'
images = []
for image_file in os.listdir(data_dir):
image_path = os.path.join(data_dir, image_file)
images.append(Image.open(image_path))
# Define CutMix function
def cutmix(images):
# Randomly select two images
index1 = random.randint(0, len(images) - 1)
index2 = random.randint(0, len(images) - 1)
image1, image2 = images[index1], images[index2]
# Generate a random bounding box
w, h = image1.size
cx, cy = random.randint(0, w - 1), random.randint(0, h - 1)
bbx1, bby1 = np.clip([cx - crop_size // 2, cy - crop_size // 2], 0, [w, h])
bbx2, bby2 = np.clip([cx + crop_size // 2, cy + crop_size // 2], [0, 0], [w - 1, h - 1])
# Replace pixels within bounding box with pixels from second image
image1_array = np.array(image1)
image2_array = np.array(image2)
mixed_image_array = np.copy(image1_array)
mixed_image_array[bbx1:bbx2, bby1:bby2, :] = image2_array[bbx1:bbx2, bby1:bby2, :]
mixed_image = Image.fromarray(mixed_image_array)
return mixed_image
# Apply CutMix to images and save the results
for i, image in enumerate(images):
mixed_image = cutmix(images)
mixed_image.save(os.path.join(data_dir, f'mixed_{i}.jpg'))
CutMix图像增广(无标签,批量增广)
猜你喜欢
转载自blog.csdn.net/m0_60461719/article/details/129485764
今日推荐
周排行