用python写一下批量图像增强数据集扩比如充度增强、对比度增强、旋转图像、翻转图像、仿射变化扩充图像、错切变化扩充图像、HSV数据增强、平移扩充
时间: 2024-09-24 14:24:29 浏览: 118
在Python中,我们可以使用一些库如`PIL`(Pillow)和`OpenCV`来进行批量图像增强。这里是一个简单的例子,展示如何进行常见的数据增强操作:
```python
from PIL import Image, ImageEnhance, ImageOps
import cv2
import numpy as np
def augment_images(image_list, transform_list):
augmented_images = []
for image in image_list:
# 图像增强
enhancer_brightness = ImageEnhance.Brightness(image)
brightness_enhanced = enhancer_brightness.enhance(1.5) # 对比度增强
enhancer_contrast = ImageEnhance.Contrast(brightness_enhanced)
contrast_enhanced = enhancer_contrast.enhance(1.2)
# 旋转和翻转
rotated_image = contrast_enhanced.rotate(45) # 随机角度旋转
flipped_image = rotated_image.transpose(Image.FLIP_LEFT_RIGHT) # 水平翻转
# 仿射变换和错切变化
width, height = flipped_image.size
center = (width // 2, height // 2)
rotation_matrix = cv2.getRotationMatrix2D(center, 45, 1.0)
transformed_image = cv2.warpAffine(np.array(flipped_image), rotation_matrix, (width, height))
# HSV数据增强
hsv_image = cv2.cvtColor(transformed_image, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv_image)
lower_saturation = np.clip(s - 50, 0, 255).astype('uint8')
upper_saturation = np.clip(s + 50, 0, 255).astype('uint8')
hsv_image = cv2.merge((h, upper_saturation, v))
# 平移变换
dx, dy = np.random.randint(-5, 6, size=2) # 随机平移范围
translation_matrix = np.float32([[1, 0, dx], [0, 1, dy]])
translated_image = cv2.warpAffine(hsv_image, translation_matrix, (width, height))
augmented_images.append(translated_image)
return augmented_images
# 示例:处理一张图片并生成增强后的图片列表
original_image = Image.open("example.jpg")
augmented_dataset = augment_images([original_image], [True] * len(original_image))
# 打印增强后的图片数量
print(f"增强后的图片数量:{len(augmented_dataset)}")
#
阅读全文