I want to augment my nifti by random replace to make ai look at different part and increase image dataset. So I random replace brain volume with black cube. I had two way, one is to simple replace numpy array section with 0, another is make a mask with cube and apply the mask to image by maskers.NiftiMasker inverse_transform but both give the image become more pale and when I change black cube to white cube in method one it become more blacken what should I do to random apply the cube.
The method one code
def random_crop(data, save_path, save_path2):
from nilearn.masking import apply_mask
number = random.randint(10 + 1)
all_depth = data.shape[-1]
all_width = data.shape[0]
all_height = data.shape[1]
size = 8
fill_image = np.zeros((size,size,size,1), np.uint8)
data = np.expand_dims(data, axis=-1)
for i in range(1, number + 1):
# print("depth1", all_depth, all_depth - size + 1)
# print('width1', all_width, all_width - size + 1)
# print('height1', all_height, all_height - size + 1)
depth_point = random.randint(all_depth - size + 1)
width_point = random.randint(all_width - size + 1)
height_point = random.randint(all_height - size + 1)
data[height_point:height_point+size, width_point:width_point+size, depth_point:depth_point+size] = fill_image
data = nib.Nifti2Image(data, affine=np.eye(4))
return data
the method two code
def random_crop(data, save_path, save_path2):
from nilearn.masking import apply_mask
number = random.randint(10 + 1)
all_depth = data.shape[-1]
all_width = data.shape[0]
all_height = data.shape[1]
size = 8
img = np.zeros((all_height,all_width,all_depth,1), np.uint8)
img.fill(1)
fill_image = np.zeros((size,size,size,1), np.uint8)
data = np.expand_dims(data, axis=-1)
for i in range(1, number + 1):
# print("depth1", all_depth, all_depth - size + 1)
# print('width1', all_width, all_width - size + 1)
# print('height1', all_height, all_height - size + 1)
depth_point = random.randint(all_depth - size + 1)
width_point = random.randint(all_width - size + 1)
height_point = random.randint(all_height - size + 1)
img[height_point:height_point+size, width_point:width_point+size, depth_point:depth_point+size] = fill_image
data2 = nib.Nifti1Image(data, affine=np.eye(4))
nib.save(data2, save_path)
data2 = nilearn.image.load_img(save_path)
img2 = nib.Nifti1Image(img, affine=np.eye(4))
nib.save(img2, save_path2)
img2 = nilearn.image.load_img(save_path2)
# print(data2.shape)
# print(img2.shape)
masker = maskers.NiftiMasker(mask_img=img2)
data3 = masker.fit_transform(data2)
data3 = masker.inverse_transform(data3)
return data3
If you have other way of random replace or suggest library I also interest but not really crop the image because it can’t put it in my model. For 3D augment library torchio only have random swap that not met my interest so I have to write myself.