File size: 15,837 Bytes
232c308 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 | import os
import pickle
import nibabel as nib
import numpy as np
def load_pickle(file: str, mode: str = 'rb'):
"""
Load and return a Python object from a pickle file.
Parameters:
- file (str): The path to the pickle file.
- mode (str): The mode in which to open the file. Defaults to 'rb' (read binary).
Returns:
- The object loaded from the pickle file.
"""
with open(file, mode) as f:
a = pickle.load(f) # Load the object from the pickle file
return a # Return the loaded object
def readDir(path, num):
"""
Read a specific subdirectory from the given path.
Parameters:
- path (str): The directory path to read.
- num (int): The index of the subdirectory to retrieve.
Returns:
- im (list): A list containing the name of the specified subdirectory.
"""
im = []
k = 0 # Initialize a counter
for root in os.walk(path): # Traverse the directory tree
if k == 0:
im.append(root[num]) # Append the nth subdirectory
k = k + 1 # Increment the counter to avoid further processing
if k == 1:
continue # Skip processing other directories
return im # Return the list containing the desired subdirectory
def load_nii_affine(filename):
"""
Load a NIfTI file and return its data and affine matrix.
If the file does not exist, returns a default array and an identity matrix.
"""
if not os.path.exists(filename):
# FIX: Return a blank 3D tensor so the cropper has all 3 dimensions
return np.zeros((160, 192, 160), dtype=np.float32), np.eye(4)
nii = nib.load(filename) # Load the NIfTI file
data = nii.get_fdata() # Retrieve the image data as a floating-point array
affine = nii.affine # Retrieve the affine transformation matrix
nii.uncache() # Uncache the NIfTI object to free memory
return data, affine # Return the data and affine matrix
def get_rectangle_3d(mask):
"""
Determine the bounding box coordinates of the non-zero region in a 3D mask.
Parameters:
- mask (numpy.ndarray): A 3D mask array where non-zero values indicate the region of interest.
Returns:
- min_x, max_x, min_y, max_y, min_z, max_z (int): The minimum and maximum indices along each axis that contain non-zero values.
"""
mask_size = mask.shape # Get the shape of the mask
min_x, min_y, min_z = mask_size[0], mask_size[1], mask_size[2] # Initialize minimum indices
max_x, max_y, max_z = 0, 0, 0 # Initialize maximum indices
# Iterate through each voxel in the mask to find the bounding box
for index_i in range(mask_size[0]):
for index_j in range(mask_size[1]):
for index_k in range(mask_size[2]):
if mask[index_i][index_j][index_k] > 0: # Check if the voxel is part of the region of interest
# Update minimum indices
if min_x > index_i:
min_x = index_i
if min_y > index_j:
min_y = index_j
if min_z > index_k:
min_z = index_k
# Update maximum indices
if max_x < index_i:
max_x = index_i
if max_y < index_j:
max_y = index_j
if max_z < index_k:
max_z = index_k
return min_x, max_x, min_y, max_y, min_z, max_z # Return the bounding box coordinates
def Padding3d(data, padding_shape=(160, 192, 160)):
"""
Pad a 3D array to the specified shape with zeros, centering the original data.
Parameters:
- data (numpy.ndarray): The 3D array to pad.
- padding_shape (tuple): The desired output shape after padding. Defaults to (160, 192, 160).
Returns:
- data (numpy.ndarray): The padded 3D array.
"""
# Pre-allocate the final padded array to prevent memory fragmentation
data_padded = np.zeros(padding_shape, dtype=np.float32)
# Calculate padding sizes for each dimension
padding_h, padding_w, padding_d = (np.array(padding_shape) - np.array(data.shape)) // 2
# Define end indices
end_h = padding_h + data.shape[0]
end_w = padding_w + data.shape[1]
end_d = padding_d + data.shape[2]
# Assign the original data into the center of the padded array directly
data_padded[padding_h:end_h, padding_w:end_w, padding_d:end_d] = data
return data_padded # Return the padded data
def random_crop(img_T1C, img_T2W, mask_input_img_T1C, mask_input_img_T2W, mask, force_fg=True):
"""
Perform a random crop on the provided 3D images and masks. With a probability of 0.8,
the function crops the images and masks. If force_fg is True, the crop will include
the entire region of interest defined by the mask.
Parameters:
- img_T1C (numpy.ndarray): The T1-weighted contrast-enhanced image.
- img_T2W (numpy.ndarray): The T2-weighted image.
- mask_input_img_T1C (numpy.ndarray): The mask corresponding to img_T1C.
- mask_input_img_T2W (numpy.ndarray): The mask corresponding to img_T2W.
- mask (numpy.ndarray): The primary mask indicating the region of interest (e.g., tumor).
- force_fg (bool): Whether to force the crop to include the foreground (region of interest). Defaults to True.
Returns:
- tuple: A tuple containing the cropped (and possibly padded) images and masks:
- crop_img_T1C (numpy.ndarray)
- crop_img_T2W (numpy.ndarray)
- mask_input_img_T1C (numpy.ndarray)
- mask_input_img_T2W (numpy.ndarray)
- crop_mask (numpy.ndarray)
If the random probability check fails (20% chance), the original images and masks are returned.
"""
P = np.random.random() # Generate a random float between 0 and 1
if P < 0.8: # 80% chance to perform cropping
shape_im = img_T1C.shape # Get the shape of the input images
crop_size = shape_im # Set the crop size to the entire image size
# Calculate lower and upper bounds for cropping along each axis
lb_x = 0
ub_x = shape_im[0] - crop_size[0] // 2
lb_y = 0
ub_y = shape_im[1] - crop_size[1] // 2
lb_z = 0
ub_z = shape_im[2] - crop_size[2] // 2
if force_fg:
# Get the bounding box coordinates of the region of interest from the mask
P_minx, P_max, P_miny, P_maxy, P_minz, P_maxz = get_rectangle_3d(mask)
# Randomly choose the lower bound of the crop to ensure it includes the entire tumor region
bbox_x_lb = np.random.randint(0, P_minx + 1)
bbox_y_lb = np.random.randint(0, P_miny + 1)
bbox_z_lb = np.random.randint(0, P_minz + 1)
else:
# Otherwise, randomly choose the lower bound within the specified range
bbox_x_lb = np.random.randint(lb_x, ub_x + 1)
bbox_y_lb = np.random.randint(lb_y, ub_y + 1)
bbox_z_lb = np.random.randint(lb_z, ub_z + 1)
# Define the upper bounds of the crop based on the lower bounds and crop size
bbox_x_ub = bbox_x_lb + crop_size[0]
bbox_y_ub = bbox_y_lb + crop_size[1]
bbox_z_ub = bbox_z_lb + crop_size[2]
# Adjust the crop boundaries to ensure they are within the image dimensions
valid_bbox_x_lb = max(0, bbox_x_lb)
valid_bbox_x_ub = min(shape_im[0], bbox_x_ub)
valid_bbox_y_lb = max(0, bbox_y_lb)
valid_bbox_y_ub = min(shape_im[1], bbox_y_ub)
valid_bbox_z_lb = max(0, bbox_z_lb)
valid_bbox_z_ub = min(shape_im[2], bbox_z_ub)
# Crop the T1C image
crop_img_T1C = np.copy(img_T1C[valid_bbox_x_lb:valid_bbox_x_ub,
valid_bbox_y_lb:valid_bbox_y_ub,
valid_bbox_z_lb:valid_bbox_z_ub])
# Crop the T2W image
crop_img_T2W = np.copy(img_T2W[valid_bbox_x_lb:valid_bbox_x_ub,
valid_bbox_y_lb:valid_bbox_y_ub,
valid_bbox_z_lb:valid_bbox_z_ub])
# Crop the mask corresponding to img_T1C
mask_input_img_T1C = np.copy(mask_input_img_T1C[valid_bbox_x_lb:valid_bbox_x_ub,
valid_bbox_y_lb:valid_bbox_y_ub,
valid_bbox_z_lb:valid_bbox_z_ub])
# Crop the mask corresponding to img_T2W
mask_input_img_T2W = np.copy(mask_input_img_T2W[valid_bbox_x_lb:valid_bbox_x_ub,
valid_bbox_y_lb:valid_bbox_y_ub,
valid_bbox_z_lb:valid_bbox_z_ub])
# Crop the primary mask
crop_mask = np.copy(mask[valid_bbox_x_lb:valid_bbox_x_ub,
valid_bbox_y_lb:valid_bbox_y_ub,
valid_bbox_z_lb:valid_bbox_z_ub])
# Pad the cropped images and masks to restore them to the original shape
crop_img_T1C = Padding3d(crop_img_T1C, shape_im)
crop_img_T2W = Padding3d(crop_img_T2W, shape_im)
mask_input_img_T1C = Padding3d(mask_input_img_T1C, shape_im)
mask_input_img_T2W = Padding3d(mask_input_img_T2W, shape_im)
crop_mask = Padding3d(crop_mask, shape_im)
# Return the cropped (and padded) images and masks
return crop_img_T1C, crop_img_T2W, mask_input_img_T1C, mask_input_img_T2W, crop_mask
else:
# With 20% probability, return the original images and masks without cropping
return img_T1C, img_T2W, mask_input_img_T1C, mask_input_img_T2W, mask
def load_mask(path):
"""
Load the mask image from the specified path.
Parameters:
- path (str): The directory path where 'mask.nii' is located.
Returns:
- mask (numpy.ndarray): The mask data as a floating-point array.
"""
mask_img_path = os.path.join(path, 'mask.nii.gz') # Construct the mask file path
if not os.path.exists(mask_img_path):
mask_img_path = os.path.join(path, 'mask.nii')
mask, _ = load_nii_affine(mask_img_path) # Load the mask data and affine matrix
mask = (mask > 0)
mask = np.array(mask, dtype=np.float32) # Convert the mask to a float array
return mask # Return the mask
def load_img(path, type):
"""
Load and preprocess an image from a NIfTI file.
Parameters:
- path (str): The directory path where the NIfTI file is located.
- type (str): The base name of the NIfTI file (without the '.nii' extension).
Returns:
- img (numpy.ndarray): The normalized image data.
- img_mask (numpy.ndarray): A binary mask indicating non-zero regions in the image.
- affine (numpy.ndarray): The affine transformation matrix of the image.
"""
# Construct the full file path by combining the directory path and file type
full_path = os.path.join(path, f'{type}.nii.gz')
if not os.path.exists(full_path):
full_path = os.path.join(path, f'{type}.nii')
img, affine = load_nii_affine(full_path) # Load the image data and affine matrix
img = np.array(img, dtype=np.float32) # Ensure the image data is in floating-point format
# Create a binary mask where pixels with values greater than 0 are marked as True
img_mask = (img > 0)
# Define a small constant to prevent division by zero during normalization
smooth = 1e-8
# Normalize the image data: subtract the mean and divide by the standard deviation
img[img_mask] = (img[img_mask] - img[img_mask].mean()) * 1.0 / (img[img_mask].std() + smooth)
# Convert the binary mask to a floating-point array
img_mask = np.array(img_mask, dtype=np.float32) # <--- CHANGED: float to np.float32
return img, img_mask, affine # Return the normalized image, mask, and affine matrix
def get_transimg(img_T1C_in, img_T2W_in, mask_input_T1C_in, mask_input_T2W_in, mask_seg_in):
"""
Perform random cropping and prepare image and mask tensors for training.
Args:
img_T1C_in (numpy.ndarray): T1C modality image.
img_T2W_in (numpy.ndarray): T2W modality image.
mask_input_T1C_in (numpy.ndarray): Mask for T1C image.
mask_input_T2W_in (numpy.ndarray): Mask for T2W image.
mask_seg_in (numpy.ndarray): Segmentation mask.
Returns:
tuple: Processed images and masks.
"""
# Apply random cropping to all inputs
img_T1C, img_T2W, mask_input_T1C, mask_input_T2W, mask_seg = random_crop(
img_T1C_in, img_T2W_in,
mask_input_T1C_in, mask_input_T2W_in,
mask_seg_in
)
# Combine input masks to create a unified mask
mask_input_combined = (mask_input_T1C + mask_input_T2W) > 0
mask_input_combined = mask_input_combined.astype(np.float32) # <--- CHANGED: float to np.float32
# Create original, positive, and negative masks based on segmentation
mask_original = np.ones_like(mask_input_combined) * mask_input_combined
mask_positive = mask_seg * mask_input_combined
# Force 32-bit to save 50% RAM and prevent the MemoryError
# --- MEMORY-SAFE IN-PLACE OPERATIONS ---
# We allocate mask_negative ONCE. We then modify it in-place
# to avoid creating temporary objects that cause allocation errors.
# Force 32-bit
mask_seg = mask_seg.astype(np.float32)
mask_input_combined = mask_input_combined.astype(np.float32)
# In-place calculation:
# 1. mask_negative = mask_seg * mask_input_combined
# 2. mask_negative = mask_input_combined - mask_negative
# This is mathematically identical to (1 - mask_seg) * input
mask_negative = np.multiply(mask_seg, mask_input_combined)
np.subtract(mask_input_combined, mask_negative, out=mask_negative)
# Prepare image data as a list of modalities
images = [img_T1C, img_T2W]
# Prepare segmentation masks
masks = [mask_original, mask_positive, mask_negative]
return images, masks
def default_loader(path):
"""
Load and process training images and masks from a given path.
Args:
path (str): Path to the image data.
Returns:
tuple: Processed images and masks for training.
"""
# Load T1C and T2W images with their masks and affine transformations
img_T1C, mask_input_T1C, affine = load_img(path, 'T1C')
img_T2W, mask_input_T2W, _ = load_img(path, 'T2')
# Load segmentation mask and convert to binary format
mask_seg = load_mask(path)
mask_seg = (mask_seg > 0).astype(np.float32) # <--- CHANGED: float to np.float32
# Transform images and masks using the get_transimg function
imgs_k_img, imgs_k_mask = get_transimg(
img_T1C, img_T2W,
mask_input_T1C, mask_input_T2W,
mask_seg
)
return imgs_k_img, imgs_k_mask
def default_loader_test(path):
"""
Load and process test images and masks from a given path.
Args:
path (str): Path to the image data.
Returns:
tuple: Processed images and masks for testing.
"""
# Load T1C and T2W images with their masks and affine transformations
img_T1C, mask_input_T1C, affine = load_img(path, 'T1C')
img_T2W, mask_input_T2W, _ = load_img(path, 'T2')
# Combine input masks to create a unified mask
mask_input_combined = (mask_input_T1C + mask_input_T2W) > 0
mask_input_combined = mask_input_combined.astype(np.float32) # <--- CHANGED: float to np.float32
# Create original mask based on the combined input mask
mask_original = np.ones_like(mask_input_combined) * mask_input_combined
# Prepare image data as a list of modalities
images = [img_T1C, img_T2W]
# Prepare segmentation masks
masks = [mask_original]
return images, masks |