Mingze101's picture
download
raw
3.18 kB
import argparse
import ast
import os
import numpy as np
import pandas as pd
import SimpleITK as sitk
from pathlib import Path
from tqdm import tqdm
# import multiprocessing as mp
def process_row(row):
# Set up directory parameters
VolumeName = row['VolumeName']
dir1 = VolumeName.rsplit('_', 1)[0]
dir2 = VolumeName.rsplit('_', 2)[0]
filepath = os.path.join(data_root, 'dataset/train', dir2, dir1, VolumeName)
# Read Image
image = sitk.ReadImage(filepath)
# Set Spacing
(x, y), z = map(float, ast.literal_eval(row['XYSpacing'])), row['ZSpacing']
image.SetSpacing((x,y,z))
# Set Origin
image.SetOrigin(ast.literal_eval(row['ImagePositionPatient']))
# Set Direction
orientation = ast.literal_eval(row['ImageOrientationPatient'])
row_cosine, col_cosine = orientation[:3], orientation[3:6]
z_cosine = np.cross(row_cosine, col_cosine).tolist()
image.SetDirection(row_cosine + col_cosine + z_cosine)
# Fix Rescale
RescaleIntercept = row['RescaleIntercept']
RescaleSlope = row['RescaleSlope']
adjusted_hu = image * RescaleSlope + RescaleIntercept
# Convert the image to int16
adjusted_hu = sitk.Cast(adjusted_hu, sitk.sitkInt16)
# Write Image
dirpath = os.path.dirname(filepath)
dirpath = dirpath.replace('/train/', '/train_fixed/')
Path(dirpath).mkdir(parents=True, exist_ok=True)
sitk.WriteImage(adjusted_hu, os.path.join(dirpath, os.path.basename(filepath)))
def main(metadata):
# Convert DataFrame rows to a list of Series, each representing a row
rows = [row[1] for row in metadata.iterrows()]
# Disabled as multiprocessing does not seem to play nice with SimpleITK
# TODO: leaving here as a future fix
# # Create a pool of workers, the number of workers is typically set to the number of cores
# pool = mp.Pool(mp.cpu_count())
#
# # Process each row in parallel
# for _ in tqdm(pool.imap_unordered(process_row, rows), total=len(rows)):
# pass # Just consume the iterator to update the tqdm progress bar
#
# # Close the pool and wait for the work to finish
# pool.close()
# pool.join()
for row in tqdm(rows):
process_row(row)
if __name__ == "__main__":
# Set up argument parsing
parser = argparse.ArgumentParser(description="Process a part of a DataFrame.")
parser.add_argument("part_num", type=int, default=1, help="The part number to process (1-indexed).")
parser.add_argument("total_parts", type=int, default=12, help="The total number of parts to divide the DataFrame into.")
args = parser.parse_args()
data_root = '/path/to/CT-RATE'
metadata = pd.read_csv(os.path.join(data_root, 'dataset/metadata/train_metadata.csv'))
# Calculate the number of rows in each part
total_rows = len(metadata)
part_size = total_rows // args.total_parts
remainder = total_rows % args.total_parts
# Calculate the start and end indices for the slice
start = (args.part_num - 1) * part_size + min(args.part_num - 1, remainder)
end = start + part_size + (1 if args.part_num <= remainder else 0)
main(metadata.iloc[start:end])

Xet Storage Details

Size:
3.18 kB
·
Xet hash:
d28ebb1c055ed91ceb40551745bb7a9d9b830b328e7fa6ea943ed390b8c83e3c

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.