Datasets:

Modalities:
Image
Formats:
parquet
Size:
< 1K
ArXiv:
Libraries:
Datasets
pandas
License:
YutingHe-list commited on
Commit
5d8a3c4
·
verified ·
1 Parent(s): d2e2a59

Update simnict_generator.py

Browse files
Files changed (1) hide show
  1. simnict_generator.py +271 -267
simnict_generator.py CHANGED
@@ -1,268 +1,272 @@
1
- # -*- coding = utf-8 -*-
2
-
3
- """
4
- SimNICT Dataset Generator
5
- Generates Non-Ideal measurement CT (NICT) simulations from preprocessed ICT data
6
-
7
- This script creates three types of NICT simulations:
8
- 1. Sparse-View CT (SVCT): Limited projection views (15-360 views)
9
- 2. Limited-Angle CT (LACT): Restricted angular range (75°-270°)
10
- 3. Low-Dose CT (LDCT): Reduced photon dose (5%-75% of normal dose)
11
-
12
- Usage:
13
- python simnict_generator.py
14
-
15
- Dependencies: numpy, torch, nibabel, odl, astra-toolbox, opencv-python, pillow
16
- """
17
-
18
- from __future__ import absolute_import, print_function
19
-
20
- import numpy as np
21
- import time
22
- import os
23
- import nibabel as nib
24
- import odl
25
- import random
26
- import astra
27
-
28
-
29
- # Dataset configuration
30
- DATASETS = ['AMOS', 'COVID_19_NY_SBU', 'CT Images in COVID-19', 'CT_COLONOGRAPHY', 'LNDb', 'LUNA', 'MELA', 'STOIC']
31
-
32
- # Path configuration
33
- INPUT_PATH = 'M:/' # Original ICT data path
34
- OUTPUT_SVCT = 'K:/SpV/' # Sparse-view CT output path
35
- OUTPUT_LACT = 'K:/LmV/' # Limited-angle CT output path
36
- OUTPUT_LDCT = 'K:/LD/' # Low-dose CT output path
37
-
38
- # Simulation parameter ranges
39
- SVCT_VIEW_RANGE = (15, 360) # Number of projection views
40
- LACT_ANGLE_RANGE = (75, 270) # Angular range in degrees
41
- LDCT_DOSE_RANGE = (5, 75) # Dose percentage
42
-
43
-
44
- def process_dataset(input_path, dataset_name):
45
- """
46
- Process a complete dataset to generate NICT simulations
47
-
48
- Args:
49
- input_path (str): Path to input ICT data
50
- dataset_name (str): Name of the dataset to process
51
- """
52
- ict_path = os.path.join(input_path, dataset_name, "int16/")
53
-
54
- if not os.path.exists(ict_path):
55
- print(f"Warning: Path {ict_path} does not exist, skipping {dataset_name}")
56
- return
57
-
58
- # Create output directories
59
- for output_path in [OUTPUT_SVCT, OUTPUT_LACT, OUTPUT_LDCT]:
60
- os.makedirs(os.path.join(output_path, dataset_name, "int16/"), exist_ok=True)
61
-
62
- files = os.listdir(ict_path)
63
- num_files = len(files)
64
- print(f"Processing {dataset_name}: {num_files} files")
65
-
66
- for i, filename in enumerate(files):
67
- print(f"Processing {dataset_name} - File {i+1}/{num_files}: {filename}")
68
-
69
- # Load ICT volume
70
- ict_file_path = os.path.join(ict_path, filename)
71
- image_obj = nib.load(ict_file_path)
72
- ict_volume = image_obj.get_fdata() + 1024 # Convert to [0, 4096] range
73
- ict_volume[ict_volume < 0] = 0
74
-
75
- L, W, S = ict_volume.shape
76
-
77
- # Initialize output volumes
78
- svct_volume = np.zeros((L, W, S), dtype=np.int16)
79
- lact_volume = np.zeros((L, W, S), dtype=np.int16)
80
- ldct_volume = np.zeros((L, W, S), dtype=np.int16)
81
-
82
- # Process each slice
83
- for slice_idx in range(S):
84
- ict_slice = ict_volume[:, :, slice_idx]
85
-
86
- # Generate SVCT with random view number
87
- svct_views = random.randint(*SVCT_VIEW_RANGE)
88
- svct_slice = create_sparse_view_ct(ict_slice, L, W, svct_views)
89
- svct_volume[:, :, slice_idx] = svct_slice
90
-
91
- # Generate LACT with random angular range
92
- lact_angle = random.randint(*LACT_ANGLE_RANGE)
93
- lact_slice = create_limited_angle_ct(ict_slice, L, W, lact_angle)
94
- lact_volume[:, :, slice_idx] = lact_slice
95
-
96
- # Generate LDCT with random dose level
97
- ldct_dose = random.randint(*LDCT_DOSE_RANGE)
98
- ldct_slice = create_low_dose_ct(ict_slice - 1024, L, W, ldct_dose) # Convert back to [-1024, 3072]
99
- ldct_volume[:, :, slice_idx] = ldct_slice
100
-
101
- # Save NICT volumes
102
- save_nict_volume(svct_volume, OUTPUT_SVCT, dataset_name, filename, volume_type="SVCT")
103
- save_nict_volume(lact_volume, OUTPUT_LACT, dataset_name, filename, volume_type="LACT")
104
- save_nict_volume(ldct_volume, OUTPUT_LDCT, dataset_name, filename, volume_type="LDCT")
105
-
106
-
107
- def save_nict_volume(volume, output_path, dataset_name, filename, volume_type):
108
- """Save NICT volume to NIfTI format"""
109
- if volume_type in ["SVCT", "LACT"]:
110
- # Convert from [0, 4096] to [-1024, 3072] range
111
- volume_output = volume - 1024
112
- volume_output[volume_output < -1024] = -1024
113
- else: # LDCT
114
- # Already in [-1024, 3072] range
115
- volume_output = volume
116
- volume_output[volume_output < -1024] = -1024
117
-
118
- nifti_image = nib.Nifti1Image(volume_output, np.eye(4))
119
- output_file = os.path.join(output_path, dataset_name, "int16/", filename)
120
- nib.save(nifti_image, output_file)
121
-
122
-
123
- def create_sparse_view_ct(ict_slice, height, width, num_views):
124
- """
125
- Generate Sparse-View CT using ODL
126
-
127
- Args:
128
- ict_slice: Input ICT slice [0, 4096]
129
- height, width: Image dimensions
130
- num_views: Number of projection views
131
- Returns:
132
- Reconstructed sparse-view CT slice
133
- """
134
- # Create reconstruction space
135
- reco_space = odl.uniform_discr(
136
- min_pt=[-height/4, -width/4],
137
- max_pt=[height/4, width/4],
138
- shape=[height, width],
139
- dtype='float32'
140
- )
141
-
142
- # Define geometry with limited views
143
- angle_partition = odl.uniform_partition(0, 2 * np.pi, num_views)
144
- detector_partition = odl.uniform_partition(-360, 360, 1024)
145
- geometry = odl.tomo.FanBeamGeometry(
146
- angle_partition, detector_partition,
147
- src_radius=1270, det_radius=870
148
- )
149
-
150
- # Create ray transform and reconstruct
151
- ray_trafo = odl.tomo.RayTransform(reco_space, geometry)
152
- projection = ray_trafo(ict_slice.astype('float32'))
153
- fbp = odl.tomo.fbp_op(ray_trafo)
154
- reconstruction = fbp(projection)
155
-
156
- return reconstruction
157
-
158
-
159
- def create_limited_angle_ct(ict_slice, height, width, angle_range):
160
- """
161
- Generate Limited-Angle CT using ODL
162
-
163
- Args:
164
- ict_slice: Input ICT slice [0, 4096]
165
- height, width: Image dimensions
166
- angle_range: Angular range in degrees
167
- Returns:
168
- Reconstructed limited-angle CT slice
169
- """
170
- # Create reconstruction space
171
- reco_space = odl.uniform_discr(
172
- min_pt=[-height/4, -width/4],
173
- max_pt=[height/4, width/4],
174
- shape=[height, width],
175
- dtype='float32'
176
- )
177
-
178
- # Define geometry with limited angular range
179
- angle_fraction = angle_range / 360
180
- num_angles = int(720 * angle_fraction)
181
- angle_partition = odl.uniform_partition(0, 2 * np.pi * angle_fraction, num_angles)
182
- detector_partition = odl.uniform_partition(-360, 360, 1024)
183
- geometry = odl.tomo.FanBeamGeometry(
184
- angle_partition, detector_partition,
185
- src_radius=1270, det_radius=870
186
- )
187
-
188
- # Create ray transform and reconstruct
189
- ray_trafo = odl.tomo.RayTransform(reco_space, geometry)
190
- projection = ray_trafo(ict_slice.astype('float32'))
191
- fbp = odl.tomo.fbp_op(ray_trafo)
192
- reconstruction = fbp(projection)
193
-
194
- return reconstruction
195
-
196
-
197
- def create_low_dose_ct(ict_slice, height, width, dose_percentage):
198
- """
199
- Generate Low-Dose CT using ASTRA with Poisson noise simulation
200
-
201
- Args:
202
- ict_slice: Input ICT slice [-1024, 3072]
203
- height, width: Image dimensions
204
- dose_percentage: Dose level as percentage of normal dose
205
- Returns:
206
- Reconstructed low-dose CT slice
207
- """
208
- dose_fraction = dose_percentage / 100.0
209
-
210
- # Convert to attenuation coefficients
211
- u = 0.0192 # Linear attenuation coefficient
212
- attenuation_map = ict_slice * u / 1000.0 + u
213
-
214
- # ASTRA geometry setup
215
- vol_geom = astra.create_vol_geom([height, width])
216
- angles = np.linspace(np.pi, -np.pi, 720)
217
- proj_geom = astra.create_proj_geom(
218
- 'fanflat', 1.685839319229126, 1024, angles,
219
- 600.4500331878662, 485.1499423980713
220
- )
221
-
222
- # Create projector and forward project
223
- proj_id = astra.create_projector('cuda', proj_geom, vol_geom)
224
- operator = astra.OpTomo(proj_id)
225
-
226
- # Forward projection
227
- sinogram = operator * np.mat(attenuation_map) / 2
228
-
229
- # Add Poisson noise based on dose level
230
- noise = np.random.normal(0, 1, 720 * 1024)
231
- noise_scaling = np.sqrt((1 - dose_fraction) / dose_fraction * (np.exp(sinogram) / 1e6))
232
- noisy_sinogram = sinogram + noise * noise_scaling
233
-
234
- # Reconstruct with FBP
235
- noisy_sinogram_2d = np.reshape(noisy_sinogram, [720, -1])
236
- reconstruction = operator.reconstruct('FBP_CUDA', noisy_sinogram_2d)
237
-
238
- # Convert back to HU values
239
- reconstruction = reconstruction.reshape((height, width))
240
- return (reconstruction * 2 - u) / u * 1000
241
-
242
-
243
- def main():
244
- """Main processing function"""
245
- print('SimNICT Dataset Generator Started')
246
- start_time = time.time()
247
-
248
- # Process each dataset
249
- for dataset_name in DATASETS:
250
- print(f"\n{'='*50}")
251
- print(f"Processing Dataset: {dataset_name}")
252
- print(f"{'='*50}")
253
-
254
- try:
255
- process_dataset(INPUT_PATH, dataset_name)
256
- duration = time.time() - start_time
257
- print(f"Completed {dataset_name} in {duration:.1f} seconds")
258
- except Exception as e:
259
- print(f"Error processing {dataset_name}: {str(e)}")
260
- continue
261
-
262
- total_duration = time.time() - start_time
263
- print(f"\nSimNICT Generation Complete - Total time: {total_duration/3600:.2f} hours")
264
-
265
-
266
- if __name__ == "__main__":
267
- main()
 
 
 
 
268
 
 
1
+ # -*- coding = utf-8 -*-
2
+
3
+ """
4
+ SimNICT Dataset Generator
5
+ Generates Non-Ideal measurement CT (NICT) simulations from preprocessed ICT data
6
+
7
+ This script creates three types of NICT simulations:
8
+ 1. Sparse-View CT (SVCT): Limited projection views (15-360 views)
9
+ 2. Limited-Angle CT (LACT): Restricted angular range (75°-270°)
10
+ 3. Low-Dose CT (LDCT): Reduced photon dose (5%-75% of normal dose)
11
+
12
+ File Structure:
13
+ - Input: dataset_name/volume_xxx.nii.gz (flat structure from Internet Archive)
14
+ - Output: output_path/dataset_name/volume_xxx.nii.gz
15
+
16
+ Usage:
17
+ python simnict_generator.py
18
+
19
+ Dependencies: numpy, torch, nibabel, odl, astra-toolbox, opencv-python, pillow
20
+ """
21
+
22
+ from __future__ import absolute_import, print_function
23
+
24
+ import numpy as np
25
+ import time
26
+ import os
27
+ import nibabel as nib
28
+ import odl
29
+ import random
30
+ import astra
31
+
32
+
33
+ # Dataset configuration
34
+ DATASETS = ['AMOS', 'COVID_19_NY_SBU', 'CT Images in COVID-19', 'CT_COLONOGRAPHY', 'LNDb', 'LUNA', 'MELA', 'STOIC']
35
+
36
+ # Path configuration
37
+ INPUT_PATH = 'M:/' # Original ICT data path (downloaded from Internet Archive)
38
+ OUTPUT_SVCT = 'K:/SpV/' # Sparse-view CT output path
39
+ OUTPUT_LACT = 'K:/LmV/' # Limited-angle CT output path
40
+ OUTPUT_LDCT = 'K:/LD/' # Low-dose CT output path
41
+
42
+ # Simulation parameter ranges
43
+ SVCT_VIEW_RANGE = (15, 360) # Number of projection views
44
+ LACT_ANGLE_RANGE = (75, 270) # Angular range in degrees
45
+ LDCT_DOSE_RANGE = (5, 75) # Dose percentage
46
+
47
+
48
+ def process_dataset(input_path, dataset_name):
49
+ """
50
+ Process a complete dataset to generate NICT simulations
51
+
52
+ Args:
53
+ input_path (str): Path to input ICT data
54
+ dataset_name (str): Name of the dataset to process
55
+ """
56
+ ict_path = os.path.join(input_path, dataset_name)
57
+
58
+ if not os.path.exists(ict_path):
59
+ print(f"Warning: Path {ict_path} does not exist, skipping {dataset_name}")
60
+ return
61
+
62
+ # Create output directories
63
+ for output_path in [OUTPUT_SVCT, OUTPUT_LACT, OUTPUT_LDCT]:
64
+ os.makedirs(os.path.join(output_path, dataset_name), exist_ok=True)
65
+
66
+ files = os.listdir(ict_path)
67
+ num_files = len(files)
68
+ print(f"Processing {dataset_name}: {num_files} files")
69
+
70
+ for i, filename in enumerate(files):
71
+ print(f"Processing {dataset_name} - File {i+1}/{num_files}: {filename}")
72
+
73
+ # Load ICT volume
74
+ ict_file_path = os.path.join(ict_path, filename)
75
+ image_obj = nib.load(ict_file_path)
76
+ ict_volume = image_obj.get_fdata() + 1024 # Convert to [0, 4096] range
77
+ ict_volume[ict_volume < 0] = 0
78
+
79
+ L, W, S = ict_volume.shape
80
+
81
+ # Initialize output volumes
82
+ svct_volume = np.zeros((L, W, S), dtype=np.int16)
83
+ lact_volume = np.zeros((L, W, S), dtype=np.int16)
84
+ ldct_volume = np.zeros((L, W, S), dtype=np.int16)
85
+
86
+ # Process each slice
87
+ for slice_idx in range(S):
88
+ ict_slice = ict_volume[:, :, slice_idx]
89
+
90
+ # Generate SVCT with random view number
91
+ svct_views = random.randint(*SVCT_VIEW_RANGE)
92
+ svct_slice = create_sparse_view_ct(ict_slice, L, W, svct_views)
93
+ svct_volume[:, :, slice_idx] = svct_slice
94
+
95
+ # Generate LACT with random angular range
96
+ lact_angle = random.randint(*LACT_ANGLE_RANGE)
97
+ lact_slice = create_limited_angle_ct(ict_slice, L, W, lact_angle)
98
+ lact_volume[:, :, slice_idx] = lact_slice
99
+
100
+ # Generate LDCT with random dose level
101
+ ldct_dose = random.randint(*LDCT_DOSE_RANGE)
102
+ ldct_slice = create_low_dose_ct(ict_slice - 1024, L, W, ldct_dose) # Convert back to [-1024, 3072]
103
+ ldct_volume[:, :, slice_idx] = ldct_slice
104
+
105
+ # Save NICT volumes
106
+ save_nict_volume(svct_volume, OUTPUT_SVCT, dataset_name, filename, volume_type="SVCT")
107
+ save_nict_volume(lact_volume, OUTPUT_LACT, dataset_name, filename, volume_type="LACT")
108
+ save_nict_volume(ldct_volume, OUTPUT_LDCT, dataset_name, filename, volume_type="LDCT")
109
+
110
+
111
+ def save_nict_volume(volume, output_path, dataset_name, filename, volume_type):
112
+ """Save NICT volume to NIfTI format"""
113
+ if volume_type in ["SVCT", "LACT"]:
114
+ # Convert from [0, 4096] to [-1024, 3072] range
115
+ volume_output = volume - 1024
116
+ volume_output[volume_output < -1024] = -1024
117
+ else: # LDCT
118
+ # Already in [-1024, 3072] range
119
+ volume_output = volume
120
+ volume_output[volume_output < -1024] = -1024
121
+
122
+ nifti_image = nib.Nifti1Image(volume_output, np.eye(4))
123
+ output_file = os.path.join(output_path, dataset_name, filename)
124
+ nib.save(nifti_image, output_file)
125
+
126
+
127
+ def create_sparse_view_ct(ict_slice, height, width, num_views):
128
+ """
129
+ Generate Sparse-View CT using ODL
130
+
131
+ Args:
132
+ ict_slice: Input ICT slice [0, 4096]
133
+ height, width: Image dimensions
134
+ num_views: Number of projection views
135
+ Returns:
136
+ Reconstructed sparse-view CT slice
137
+ """
138
+ # Create reconstruction space
139
+ reco_space = odl.uniform_discr(
140
+ min_pt=[-height/4, -width/4],
141
+ max_pt=[height/4, width/4],
142
+ shape=[height, width],
143
+ dtype='float32'
144
+ )
145
+
146
+ # Define geometry with limited views
147
+ angle_partition = odl.uniform_partition(0, 2 * np.pi, num_views)
148
+ detector_partition = odl.uniform_partition(-360, 360, 1024)
149
+ geometry = odl.tomo.FanBeamGeometry(
150
+ angle_partition, detector_partition,
151
+ src_radius=1270, det_radius=870
152
+ )
153
+
154
+ # Create ray transform and reconstruct
155
+ ray_trafo = odl.tomo.RayTransform(reco_space, geometry)
156
+ projection = ray_trafo(ict_slice.astype('float32'))
157
+ fbp = odl.tomo.fbp_op(ray_trafo)
158
+ reconstruction = fbp(projection)
159
+
160
+ return reconstruction
161
+
162
+
163
+ def create_limited_angle_ct(ict_slice, height, width, angle_range):
164
+ """
165
+ Generate Limited-Angle CT using ODL
166
+
167
+ Args:
168
+ ict_slice: Input ICT slice [0, 4096]
169
+ height, width: Image dimensions
170
+ angle_range: Angular range in degrees
171
+ Returns:
172
+ Reconstructed limited-angle CT slice
173
+ """
174
+ # Create reconstruction space
175
+ reco_space = odl.uniform_discr(
176
+ min_pt=[-height/4, -width/4],
177
+ max_pt=[height/4, width/4],
178
+ shape=[height, width],
179
+ dtype='float32'
180
+ )
181
+
182
+ # Define geometry with limited angular range
183
+ angle_fraction = angle_range / 360
184
+ num_angles = int(720 * angle_fraction)
185
+ angle_partition = odl.uniform_partition(0, 2 * np.pi * angle_fraction, num_angles)
186
+ detector_partition = odl.uniform_partition(-360, 360, 1024)
187
+ geometry = odl.tomo.FanBeamGeometry(
188
+ angle_partition, detector_partition,
189
+ src_radius=1270, det_radius=870
190
+ )
191
+
192
+ # Create ray transform and reconstruct
193
+ ray_trafo = odl.tomo.RayTransform(reco_space, geometry)
194
+ projection = ray_trafo(ict_slice.astype('float32'))
195
+ fbp = odl.tomo.fbp_op(ray_trafo)
196
+ reconstruction = fbp(projection)
197
+
198
+ return reconstruction
199
+
200
+
201
+ def create_low_dose_ct(ict_slice, height, width, dose_percentage):
202
+ """
203
+ Generate Low-Dose CT using ASTRA with Poisson noise simulation
204
+
205
+ Args:
206
+ ict_slice: Input ICT slice [-1024, 3072]
207
+ height, width: Image dimensions
208
+ dose_percentage: Dose level as percentage of normal dose
209
+ Returns:
210
+ Reconstructed low-dose CT slice
211
+ """
212
+ dose_fraction = dose_percentage / 100.0
213
+
214
+ # Convert to attenuation coefficients
215
+ u = 0.0192 # Linear attenuation coefficient
216
+ attenuation_map = ict_slice * u / 1000.0 + u
217
+
218
+ # ASTRA geometry setup
219
+ vol_geom = astra.create_vol_geom([height, width])
220
+ angles = np.linspace(np.pi, -np.pi, 720)
221
+ proj_geom = astra.create_proj_geom(
222
+ 'fanflat', 1.685839319229126, 1024, angles,
223
+ 600.4500331878662, 485.1499423980713
224
+ )
225
+
226
+ # Create projector and forward project
227
+ proj_id = astra.create_projector('cuda', proj_geom, vol_geom)
228
+ operator = astra.OpTomo(proj_id)
229
+
230
+ # Forward projection
231
+ sinogram = operator * np.mat(attenuation_map) / 2
232
+
233
+ # Add Poisson noise based on dose level
234
+ noise = np.random.normal(0, 1, 720 * 1024)
235
+ noise_scaling = np.sqrt((1 - dose_fraction) / dose_fraction * (np.exp(sinogram) / 1e6))
236
+ noisy_sinogram = sinogram + noise * noise_scaling
237
+
238
+ # Reconstruct with FBP
239
+ noisy_sinogram_2d = np.reshape(noisy_sinogram, [720, -1])
240
+ reconstruction = operator.reconstruct('FBP_CUDA', noisy_sinogram_2d)
241
+
242
+ # Convert back to HU values
243
+ reconstruction = reconstruction.reshape((height, width))
244
+ return (reconstruction * 2 - u) / u * 1000
245
+
246
+
247
+ def main():
248
+ """Main processing function"""
249
+ print('SimNICT Dataset Generator Started')
250
+ start_time = time.time()
251
+
252
+ # Process each dataset
253
+ for dataset_name in DATASETS:
254
+ print(f"\n{'='*50}")
255
+ print(f"Processing Dataset: {dataset_name}")
256
+ print(f"{'='*50}")
257
+
258
+ try:
259
+ process_dataset(INPUT_PATH, dataset_name)
260
+ duration = time.time() - start_time
261
+ print(f"Completed {dataset_name} in {duration:.1f} seconds")
262
+ except Exception as e:
263
+ print(f"Error processing {dataset_name}: {str(e)}")
264
+ continue
265
+
266
+ total_duration = time.time() - start_time
267
+ print(f"\nSimNICT Generation Complete - Total time: {total_duration/3600:.2f} hours")
268
+
269
+
270
+ if __name__ == "__main__":
271
+ main()
272