此增强代码为线下增强:
增强函数:
import numpy as np
from numpy import flip
from scipy.ndimage import rotate
#将三维数据的长,高,厚度分别理解为x,y,z轴
class Aug():
def __init__(self,data):
self.data = data
#(x,y)平面上下翻转
def sx_flip(self):
sx_data = flip(self.data, 0)
return sx_data
#(x,y)平面左右翻转
def zy_flip(self):
zy_data = flip(self.data, 1)
return zy_data
#(x,y)平面前后翻转
def qh_flip(self):
qh_flip = flip(self.data, 2)
return qh_flip
#(x,y)平面即以z轴为中心左旋转90度
def x90_rotate(self):
x90_rotate = rotate(self.data, angle=90, axes=(0, 1))
return x90_rotate
#(x,y)平面向上平移10个像素
def s_translation(self):
datashape = self.data.shape
height = datashape[0]
width = datashape[1]
depth = datashape[2]
dst = np.zeros(datashape,np.uint16)
for j in range(width):
for k in range(depth):
for i in range(10,height):
dst[i - 10,j,k] = self.data[i,j,k]
s_translation = dst
return s_translation
#(x,y)平面向下平移10个像素
def x_translation(self):
datashape = self.data.shape
height = datashape[0]
width = datashape[1]
depth = datashape[2]
dst = np.zeros(datashape,np.uint16)
for j in range(width):
for k in range(depth):
for i in range(height - 10):
dst[i+10,j,k] = self.data[i,j,k]
x_translation = dst
return x_translation
#(x,y)平面向左平移10个像素
def z_translation(self):
datashape = self.data.shape
height = datashape[0]
width = datashape[1]
depth = datashape[2]
dst = np.zeros(datashape,np.uint16)
for i in range(height):
for k in range(depth):
for j in range(10,width):
dst[i,j - 10,k] = self.data[i,j,k]
z_translation = dst
return z_translation
#(x,y)平面向右平移10个像素
def y_translation(self):
datashape = self.data.shape
height = datashape[0]
width = datashape[1]
depth = datashape[2]
dst = np.zeros(datashape, np.uint16)
for i in range(height):
for k in range(depth):
for j in range(width - 10):
dst[i, j + 10, k] = self.data[i, j, k]
y_translation = dst
return y_translation
main函数:
import cv2
import os
dataset_file = 'H:/dataset/300/train5/aug/Malignant/' #待增强数据路径,mat类型
dataset_list = os.listdir(dataset_file)
aug_file = 'H:/dataset/300/train5/aug/M/' #增强后路径
for dataset in dataset_list:
data = (sio.loadmat(dataset_file+dataset))['cropped_image']
aug_data = Aug(data).sx_flip()
sio.savemat(aug_file + dataset[0:-4] + '_1', {"cropped_image":aug_data})