|
|
import glob
|
|
|
import random
|
|
|
import os
|
|
|
import cv2
|
|
|
import numpy as np
|
|
|
import tqdm
|
|
|
from matplotlib import pyplot as plt
|
|
|
|
|
|
import albumentations as A
|
|
|
|
|
|
|
|
|
def visualize(image, mask, original_image=None, original_mask=None):
|
|
|
fontsize = 18
|
|
|
|
|
|
if original_image is None and original_mask is None:
|
|
|
f, ax = plt.subplots(2, 1, figsize=(8, 8))
|
|
|
|
|
|
ax[0].imshow(image)
|
|
|
ax[1].imshow(mask)
|
|
|
else:
|
|
|
f, ax = plt.subplots(2, 2, figsize=(8, 8))
|
|
|
|
|
|
ax[0, 0].imshow(original_image)
|
|
|
ax[0, 0].set_title('Original image', fontsize=fontsize)
|
|
|
|
|
|
ax[1, 0].imshow(original_mask)
|
|
|
ax[1, 0].set_title('Original mask', fontsize=fontsize)
|
|
|
|
|
|
ax[0, 1].imshow(image)
|
|
|
ax[0, 1].set_title('Transformed image', fontsize=fontsize)
|
|
|
|
|
|
ax[1, 1].imshow(mask)
|
|
|
ax[1, 1].set_title('Transformed mask', fontsize=fontsize)
|
|
|
plt.show()
|
|
|
def augment_by_times():
|
|
|
image_path=r'C:\Users\zhang\PycharmProjects\mmsegmentation\data\mr-cardiac\mri_train_2d\image'
|
|
|
label_path=r'C:\Users\zhang\PycharmProjects\mmsegmentation\data\mr-cardiac\mri_train_2d\label'
|
|
|
|
|
|
image_paths=glob.glob(os.path.join(image_path,'*.png'))
|
|
|
|
|
|
|
|
|
times=2
|
|
|
for i in range(times):
|
|
|
for path in tqdm.tqdm(image_paths):
|
|
|
|
|
|
filename=path.split('\\')[-1]
|
|
|
|
|
|
|
|
|
image = cv2.imread(path,0)
|
|
|
mask = cv2.imread(os.path.join(label_path,filename),0)
|
|
|
|
|
|
|
|
|
|
|
|
original_height, original_width = image.shape[:2]
|
|
|
aug = A.Compose([
|
|
|
A.PadIfNeeded(min_height=128,min_width=128,value=0,p=1),
|
|
|
|
|
|
|
|
|
A.VerticalFlip(p=0.5),
|
|
|
A.RandomRotate90(p=0.5),
|
|
|
A.OneOf([
|
|
|
A.ElasticTransform(alpha=120, sigma=120 * 0.05,
|
|
|
alpha_affine=120 * 0.03, p=0.5),
|
|
|
A.GridDistortion(p=0.5),
|
|
|
A.OpticalDistortion(distort_limit=2, shift_limit=0.5, p=1)
|
|
|
], p=0.8),
|
|
|
A.CLAHE(p=0.8),
|
|
|
A.RandomBrightnessContrast(p=0.8),
|
|
|
A.RandomGamma(p=0.8)
|
|
|
]
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
augmented = aug(image=image, mask=mask)
|
|
|
|
|
|
image_heavy = augmented['image']
|
|
|
mask_heavy = augmented['mask']
|
|
|
|
|
|
label_num=len(np.unique(mask_heavy))
|
|
|
|
|
|
if label_num>=2:
|
|
|
|
|
|
cv2.imwrite(os.path.join(image_path.replace('mri_train_2d','mri_aug_2d'),f'aug{i+1}_'+filename),image_heavy)
|
|
|
cv2.imwrite(os.path.join(label_path.replace('mri_train_2d', 'mri_aug_2d'),
|
|
|
f'aug{i+1}_' + filename), mask_heavy)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
augment_by_times() |