采用随机色彩失真、随机角度旋转、随机平移、随机扩充、随机裁剪等 图像变换方法进行数据集扩充的python程序
以下是一个使用Python进行图像数据扩充的示例程序:
import os
import cv2
import random
import numpy as np
# 数据集路径和保存路径
data_path = 'path/to/dataset'
save_path = 'path/to/save'
# 图像扩充参数
rotate_range = 30 # 旋转角度范围
shift_range = 0.1 # 平移范围
zoom_range = 0.2 # 扩充范围
crop_size = 224 # 裁剪尺寸
# 加载数据集并进行扩充
for filename in os.listdir(data_path):
img = cv2.imread(os.path.join(data_path, filename))
if img is not None:
# 随机旋转
angle = random.uniform(-rotate_range, rotate_range)
rows, cols, _ = img.shape
M = cv2.getRotationMatrix2D((cols / 2, rows / 2), angle, 1)
img = cv2.warpAffine(img, M, (cols, rows))
# 随机平移
x_shift = random.uniform(-shift_range, shift_range) * cols
y_shift = random.uniform(-shift_range, shift_range) * rows
M = np.float32([[1, 0, x_shift], [0, 1, y_shift]])
img = cv2.warpAffine(img, M, (cols, rows))
# 随机扩充
h, w, _ = img.shape
zoom_scale = random.uniform(1 - zoom_range, 1 + zoom_range)
img = cv2.resize(img, (int(w * zoom_scale), int(h * zoom_scale)))
# 随机裁剪
h, w, _ = img.shape
x = random.randint(0, w - crop_size)
y = random.randint(0, h - crop_size)
img = img[y:y + crop_size, x:x + crop_size]
# 随机色彩失真
img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(img)
hue_shift = random.randint(0, 180)
h = (h + hue_shift) % 180
img = cv2.merge((h, s, v))
img = cv2.cvtColor(img, cv2.COLOR_HSV2BGR)
# 保存扩充后的图像
cv2.imwrite(os.path.join(save_path, filename), img)
该程序首先从指定路径读取图像数据集,然后对每张图像进行随机旋转、随机平移、随机扩充、随机裁剪和随机色彩失真等变换操作。最后将扩充后的图像保存到指定路径。可以根据实际需求修改扩充参数和变换操作,以获得更好的效果
原文地址: https://www.cveoy.top/t/topic/cIJB 著作权归作者所有。请勿转载和采集!