实例分割的数据增强代码
时间: 2023-09-09 21:10:30 浏览: 89
YOLOv8实例分割离线数据增强,标签可视化!
以下是一个示例数据增强代码,其中使用了常见的图像增强技术,如随机旋转、缩放、翻转、裁剪等。
```python
import random
import cv2
def random_crop(image, mask, size=(256, 256)):
h, w = image.shape[:2]
new_h, new_w = size
top = random.randint(0, h - new_h)
left = random.randint(0, w - new_w)
image = image[top: top + new_h, left: left + new_w]
mask = mask[top: top + new_h, left: left + new_w]
return image, mask
def random_rotate(image, mask, angle_range=(-30, 30)):
angle = random.uniform(angle_range[0], angle_range[1])
h, w = image.shape[:2]
center = (w / 2, h / 2)
matrix = cv2.getRotationMatrix2D(center, angle, 1.0)
image = cv2.warpAffine(image, matrix, (w, h), flags=cv2.INTER_LINEAR)
mask = cv2.warpAffine(mask, matrix, (w, h), flags=cv2.INTER_NEAREST)
return image, mask
def random_scale(image, mask, scale_range=(0.8, 1.2)):
scale = random.uniform(scale_range[0], scale_range[1])
h, w = image.shape[:2]
new_h, new_w = int(h * scale), int(w * scale)
image = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
mask = cv2.resize(mask, (new_w, new_h), interpolation=cv2.INTER_NEAREST)
return image, mask
def random_flip(image, mask, flip_prob=0.5):
if random.random() < flip_prob:
image = cv2.flip(image, 1)
mask = cv2.flip(mask, 1)
return image, mask
def apply_augmentations(image, mask):
image, mask = random_crop(image, mask)
image, mask = random_rotate(image, mask)
image, mask = random_scale(image, mask)
image, mask = random_flip(image, mask)
return image, mask
```
阅读全文