-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_roi_names_with_count.py
105 lines (83 loc) · 3.14 KB
/
get_roi_names_with_count.py
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
import os
import pandas as pd
from pydicom import dcmread
import argparse
import csv
def main():
# Initialize argument parser
parser = argparse.ArgumentParser()
parser.add_argument("image_dir", help="Path to file with all images")
parser.add_argument("output_dir", help="Path to output directory")
args = parser.parse_args()
dataPath = args.image_dir
outputPath = args.output_dir
# Extract ROI names from RTStructs in the dataset
roiNames = getRTStructsRoiNames(dataPath)
print("ROI Names Extracted Successfully")
# Ensure the output directory exists, create if not
if not os.path.exists(os.path.dirname(outputPath)):
os.makedirs(os.path.dirname(outputPath))
# Specify the CSV file name
csv_file_name = outputPath + "/roi_names.csv"
# Write ROI names and their counts to the CSV file
with open(csv_file_name, mode='w', newline='') as file:
writer = csv.writer(file)
# Write the header
writer.writerow(['roi_names', 'count'])
# Write the dictionary items as rows
for roi_name, count in sorted(roiNames.items()):
writer.writerow([roi_name, count])
print(f'CSV file "{csv_file_name}" has been created successfully.')
print("ROI Names saved to: " + outputPath)
def getRTStructsRoiNames(dataPath: str):
'''
Extracts ROI names from RTStruct files in the dataset.
Parameters
----------
dataPath : str
Path to the dataset
Returns
-------
dict
A dictionary with ROI names as keys and their counts as values
'''
# Construct the path to the imgtools file list
imageDirPath, ctDirName = os.path.split(dataPath)
imgFileListPath = os.path.join(imageDirPath + '/.imgtools/imgtools_' + ctDirName + '.csv')
if not os.path.exists(imgFileListPath):
raise FileNotFoundError(
"Output for med-imagetools not found for this image set. Check the image_dir argument or run med-imagetools.")
# Load the complete list of patient image directories from imgtools output
fullImgFileList = pd.read_csv(imgFileListPath, index_col=0)
# Extract rows corresponding to RTStruct modality
allRTStuctRows = fullImgFileList.loc[fullImgFileList['modality'] == "RTSTRUCT"]
roiNames = {}
# Iterate over each RTStruct file path and extract ROI names
for file_path in allRTStuctRows['file_path']:
rtstructFilePath = imageDirPath + "/" + file_path
result = getROINames(rtstructFilePath)
for roi in result:
if roi in roiNames:
roiNames[roi] += 1
else:
roiNames[roi] = 1
return roiNames
def getROINames(rtstructPath: str):
'''
Extracts ROI names from a single RTStruct file.
Parameters
----------
rtstructPath : str
The filepath of the RTStruct file
Returns
-------
set
A set of ROI names present in the RTStruct file
'''
# Read the RTStruct file
rtstruct = dcmread(rtstructPath, force=True)
# Extract ROI names
roi_names = set([roi.ROIName for roi in rtstruct.StructureSetROISequence])
return roi_names
if __name__ == '__main__':
main()