pydicomrt 0.10.0__py3-none-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pydicomrt/__init__.py +2 -0
- pydicomrt/ct/__init__.py +9 -0
- pydicomrt/ct/builder.py +464 -0
- pydicomrt/ct/check.py +41 -0
- pydicomrt/ct/iod.py +40 -0
- pydicomrt/dose/__init__.py +32 -0
- pydicomrt/dose/builder.py +564 -0
- pydicomrt/dose/check.py +43 -0
- pydicomrt/dose/iod.py +42 -0
- pydicomrt/dose/sitk_transform.py +149 -0
- pydicomrt/reg/__init__.py +35 -0
- pydicomrt/reg/builder.py +777 -0
- pydicomrt/reg/check.py +113 -0
- pydicomrt/reg/iod.py +171 -0
- pydicomrt/reg/method/__init__.py +13 -0
- pydicomrt/reg/method/_demons_torch.py +664 -0
- pydicomrt/reg/method/_rigid_core.py +126 -0
- pydicomrt/reg/method/_stochastic_rigid.py +330 -0
- pydicomrt/reg/method/bspline.py +426 -0
- pydicomrt/reg/method/common.py +226 -0
- pydicomrt/reg/method/demons.py +527 -0
- pydicomrt/reg/method/rigid.py +576 -0
- pydicomrt/reg/method/rigid_core.dll +0 -0
- pydicomrt/reg/method/soft_demons.py +247 -0
- pydicomrt/reg/parser.py +229 -0
- pydicomrt/reg/pipeline/__init__.py +36 -0
- pydicomrt/reg/pipeline/preprocessing.py +463 -0
- pydicomrt/reg/pipeline/registration_pipeline.py +294 -0
- pydicomrt/reg/type_transform.py +100 -0
- pydicomrt/rs/__init__.py +47 -0
- pydicomrt/rs/add_new_roi.py +89 -0
- pydicomrt/rs/builder.py +471 -0
- pydicomrt/rs/check.py +135 -0
- pydicomrt/rs/contour_process_method.py +221 -0
- pydicomrt/rs/iod.py +63 -0
- pydicomrt/rs/make_contour_sequence.py +244 -0
- pydicomrt/rs/parser.py +153 -0
- pydicomrt/rs/rs_to_volume.py +479 -0
- pydicomrt/utils/__init__.py +49 -0
- pydicomrt/utils/coordinate_transform.py +238 -0
- pydicomrt/utils/image_series_loader.py +138 -0
- pydicomrt/utils/sitk_image_process/__init__.py +11 -0
- pydicomrt/utils/sitk_image_process/bilateral_denoise_filter.py +59 -0
- pydicomrt/utils/sitk_image_process/median_denoise_filter.py +28 -0
- pydicomrt/utils/sitk_image_process/n4_bias_field_correction.py +51 -0
- pydicomrt/utils/sitk_transform.py +544 -0
- pydicomrt/utils/validate_dcm_info.py +170 -0
- pydicomrt-0.10.0.dist-info/METADATA +433 -0
- pydicomrt-0.10.0.dist-info/RECORD +52 -0
- pydicomrt-0.10.0.dist-info/WHEEL +5 -0
- pydicomrt-0.10.0.dist-info/entry_points.txt +3 -0
- pydicomrt-0.10.0.dist-info/licenses/LICENSE +21 -0
pydicomrt/__init__.py
ADDED
pydicomrt/ct/__init__.py
ADDED
pydicomrt/ct/builder.py
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
"""
|
|
2
|
+
CT Image Builder
|
|
3
|
+
Date: 2026-02-14
|
|
4
|
+
Author: higumalu
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import copy
|
|
8
|
+
import datetime
|
|
9
|
+
import logging
|
|
10
|
+
from typing import List, Sequence
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
import SimpleITK as sitk
|
|
14
|
+
from pydicom.dataset import Dataset, FileDataset, FileMetaDataset
|
|
15
|
+
from pydicom.uid import ImplicitVRLittleEndian, generate_uid
|
|
16
|
+
|
|
17
|
+
from pydicomrt.utils.sitk_transform import SimpleITKImageBuilder
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
#: Stored values are unsigned 16-bit with this intercept, so HU = stored + RESCALE_INTERCEPT.
|
|
22
|
+
RESCALE_INTERCEPT = -1024
|
|
23
|
+
_STORED_MAX = 2 ** 16 - 1
|
|
24
|
+
|
|
25
|
+
#: Which SimpleITK axis plays which DICOM role, per plane.
|
|
26
|
+
#:
|
|
27
|
+
#: DICOM counts a *row* along the column index and a *column* along the row index, and
|
|
28
|
+
#: SimpleITK reports (x, y, z) while numpy arrays come back (z, y, x). Writing the index
|
|
29
|
+
#: juggling out once, per plane, keeps the three views from drifting apart -- SAGITTAL and
|
|
30
|
+
#: CORONAL used to be swapped because each was hand-indexed separately.
|
|
31
|
+
#:
|
|
32
|
+
#: (column axis, row axis, slice-normal axis) as SimpleITK axis numbers.
|
|
33
|
+
PLANE_AXES = {
|
|
34
|
+
"AXIAL": (0, 1, 2), # normal along z
|
|
35
|
+
"CORONAL": (0, 2, 1), # normal along y
|
|
36
|
+
"SAGITTAL": (1, 2, 0), # normal along x
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class CTBuilder:
|
|
41
|
+
"""
|
|
42
|
+
Emit a CT Image series from a volume, borrowing patient and study context from a
|
|
43
|
+
reference series.
|
|
44
|
+
|
|
45
|
+
The output is DERIVED/SECONDARY: it is a rendering of a volume, not an acquisition.
|
|
46
|
+
It gets its own SeriesInstanceUID, so it cannot be mistaken for -- or merged into --
|
|
47
|
+
the acquired series it borrowed context from.
|
|
48
|
+
|
|
49
|
+
Parameters
|
|
50
|
+
----------
|
|
51
|
+
image_series : list of Dataset
|
|
52
|
+
Reference slices supplying patient identity, study and frame of reference. Only
|
|
53
|
+
the first is read for context unless :meth:`set_copy_all_attributes` is on.
|
|
54
|
+
|
|
55
|
+
Methods
|
|
56
|
+
-------
|
|
57
|
+
set_volume(sitk_image)
|
|
58
|
+
The volume to slice, in HU. Required (or ``set_volume_from_array``).
|
|
59
|
+
set_volume_from_array(volume, origin, spacing, direction)
|
|
60
|
+
The same, from numpy plus geometry.
|
|
61
|
+
set_plane(plan_view)
|
|
62
|
+
AXIAL, CORONAL or SAGITTAL. Default AXIAL.
|
|
63
|
+
set_copy_all_attributes(copy_all_attributes)
|
|
64
|
+
Inherit every attribute from the reference series.
|
|
65
|
+
set_uid_prefix(uid_prefix)
|
|
66
|
+
Set the UID root.
|
|
67
|
+
build()
|
|
68
|
+
Slice the volume into one ``Dataset`` per slice.
|
|
69
|
+
|
|
70
|
+
Raises
|
|
71
|
+
------
|
|
72
|
+
ValueError
|
|
73
|
+
If ``image_series`` is empty.
|
|
74
|
+
|
|
75
|
+
See Also
|
|
76
|
+
--------
|
|
77
|
+
check_ct_iod : Validate the emitted slices.
|
|
78
|
+
image_series_to_sitk_image : The reverse direction.
|
|
79
|
+
|
|
80
|
+
Notes
|
|
81
|
+
-----
|
|
82
|
+
Values are stored as unsigned 16-bit with a -1024 intercept, so the representable
|
|
83
|
+
range is -1024 to 64511 HU. Values outside it are clipped, not wrapped.
|
|
84
|
+
|
|
85
|
+
Examples
|
|
86
|
+
--------
|
|
87
|
+
>>> slices = ( # doctest: +SKIP
|
|
88
|
+
... CTBuilder(reference_series)
|
|
89
|
+
... .set_volume(sitk_image)
|
|
90
|
+
... .set_plane("AXIAL")
|
|
91
|
+
... .build()
|
|
92
|
+
... )
|
|
93
|
+
>>> for i, s in enumerate(slices): # doctest: +SKIP
|
|
94
|
+
... s.save_as(f"ct_{i:04d}.dcm", enforce_file_format=True)
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
def __init__(self, image_series: List[Dataset]):
|
|
98
|
+
if not image_series:
|
|
99
|
+
raise ValueError("image_series must be non-empty")
|
|
100
|
+
self.image_series = list(image_series)
|
|
101
|
+
self.uid_prefix = "1.2.826.0.1.3680043.8.498." # PYDICOM_ROOT_UID
|
|
102
|
+
self.ref_ds = self.image_series[0]
|
|
103
|
+
self._base_file_name = "ct_image"
|
|
104
|
+
self.template_ds = copy.deepcopy(self.image_series[0])
|
|
105
|
+
self.volume_image = None
|
|
106
|
+
self.plan_view = "AXIAL"
|
|
107
|
+
self.copy_all_attributes = False
|
|
108
|
+
|
|
109
|
+
def set_uid_prefix(self, uid_prefix: str) -> "CTBuilder":
|
|
110
|
+
"""
|
|
111
|
+
Set the root under which generated UIDs are minted.
|
|
112
|
+
|
|
113
|
+
Parameters
|
|
114
|
+
----------
|
|
115
|
+
uid_prefix : str
|
|
116
|
+
Organisation UID root, dot-terminated. Unlike the RTSTRUCT and dose builders,
|
|
117
|
+
this one does **not** read ``DICOM_UID_PREFIX``; it defaults to pydicom's
|
|
118
|
+
root, which you do not own.
|
|
119
|
+
|
|
120
|
+
Returns
|
|
121
|
+
-------
|
|
122
|
+
CTBuilder
|
|
123
|
+
self, so calls chain.
|
|
124
|
+
"""
|
|
125
|
+
self.uid_prefix = uid_prefix
|
|
126
|
+
return self
|
|
127
|
+
|
|
128
|
+
def set_volume(self, sitk_image: sitk.Image) -> "CTBuilder":
|
|
129
|
+
"""
|
|
130
|
+
Set the volume to slice.
|
|
131
|
+
|
|
132
|
+
Parameters
|
|
133
|
+
----------
|
|
134
|
+
sitk_image : sitk.Image
|
|
135
|
+
3D. Intensities are treated as Hounsfield units and written with a -1024
|
|
136
|
+
intercept, so values outside -1024 to 64511 HU are clipped. Geometry --
|
|
137
|
+
origin, spacing, direction -- is taken from the image and becomes the output
|
|
138
|
+
series' geometry.
|
|
139
|
+
|
|
140
|
+
Returns
|
|
141
|
+
-------
|
|
142
|
+
CTBuilder
|
|
143
|
+
self, so calls chain.
|
|
144
|
+
|
|
145
|
+
Raises
|
|
146
|
+
------
|
|
147
|
+
ValueError
|
|
148
|
+
If the image is not 3D.
|
|
149
|
+
"""
|
|
150
|
+
if sitk_image.GetDimension() != 3:
|
|
151
|
+
raise ValueError(f"volume must be 3D, got {sitk_image.GetDimension()}D")
|
|
152
|
+
self.volume_image = sitk_image
|
|
153
|
+
return self
|
|
154
|
+
|
|
155
|
+
def set_volume_from_array(
|
|
156
|
+
self,
|
|
157
|
+
volume: np.ndarray,
|
|
158
|
+
origin: Sequence[float],
|
|
159
|
+
spacing: Sequence[float],
|
|
160
|
+
direction: Sequence[float],
|
|
161
|
+
) -> "CTBuilder":
|
|
162
|
+
"""
|
|
163
|
+
Set the volume from a numpy array plus its geometry.
|
|
164
|
+
|
|
165
|
+
Parameters
|
|
166
|
+
----------
|
|
167
|
+
volume : np.ndarray
|
|
168
|
+
3D, ``(slice, row, column)``. Treated as HU.
|
|
169
|
+
origin : sequence of float
|
|
170
|
+
Patient coordinates of voxel ``[0, 0, 0]``, in mm.
|
|
171
|
+
spacing : sequence of float
|
|
172
|
+
``(x, y, z)`` in mm -- SimpleITK's order, not DICOM's ``[row, column]``.
|
|
173
|
+
direction : sequence of float
|
|
174
|
+
3x3 or flat 9-sequence, axis vectors in **columns**.
|
|
175
|
+
|
|
176
|
+
Returns
|
|
177
|
+
-------
|
|
178
|
+
CTBuilder
|
|
179
|
+
self, so calls chain.
|
|
180
|
+
|
|
181
|
+
Raises
|
|
182
|
+
------
|
|
183
|
+
ValueError
|
|
184
|
+
If the volume is not 3D or any geometry argument is the wrong shape.
|
|
185
|
+
|
|
186
|
+
See Also
|
|
187
|
+
--------
|
|
188
|
+
set_volume : When you already have a ``sitk.Image``.
|
|
189
|
+
"""
|
|
190
|
+
return self.set_volume(
|
|
191
|
+
SimpleITKImageBuilder()
|
|
192
|
+
.set_volume(volume)
|
|
193
|
+
.set_origin(origin)
|
|
194
|
+
.set_spacing(spacing)
|
|
195
|
+
.set_direction(direction)
|
|
196
|
+
.build()
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
def set_plane(self, plan_view: str) -> "CTBuilder":
|
|
200
|
+
"""
|
|
201
|
+
Choose the plane each slice lies in.
|
|
202
|
+
|
|
203
|
+
Parameters
|
|
204
|
+
----------
|
|
205
|
+
plan_view : {"AXIAL", "CORONAL", "SAGITTAL"}
|
|
206
|
+
Case-insensitive. Named for the plane each slice lies *in*, so the axis the
|
|
207
|
+
slices stack along is the one **not** in the name: axial stacks along z,
|
|
208
|
+
coronal along y, sagittal along x. Default AXIAL.
|
|
209
|
+
|
|
210
|
+
Returns
|
|
211
|
+
-------
|
|
212
|
+
CTBuilder
|
|
213
|
+
self, so calls chain.
|
|
214
|
+
|
|
215
|
+
Raises
|
|
216
|
+
------
|
|
217
|
+
ValueError
|
|
218
|
+
If ``plan_view`` is not one of the three.
|
|
219
|
+
|
|
220
|
+
Notes
|
|
221
|
+
-----
|
|
222
|
+
Reslicing does not resample. A coronal series from an anisotropic axial volume
|
|
223
|
+
inherits the slice spacing as its in-plane row spacing, so it will look coarse in
|
|
224
|
+
one direction. Resample to isotropic first if that matters.
|
|
225
|
+
"""
|
|
226
|
+
plan_view = plan_view.upper()
|
|
227
|
+
if plan_view not in PLANE_AXES:
|
|
228
|
+
raise ValueError(
|
|
229
|
+
f"Invalid plan view: {plan_view!r}; expected one of {sorted(PLANE_AXES)}"
|
|
230
|
+
)
|
|
231
|
+
self.plan_view = plan_view
|
|
232
|
+
return self
|
|
233
|
+
|
|
234
|
+
def set_copy_all_attributes(self, copy_all_attributes: bool) -> "CTBuilder":
|
|
235
|
+
"""
|
|
236
|
+
Copy every attribute from the reference series instead of building fresh.
|
|
237
|
+
|
|
238
|
+
Parameters
|
|
239
|
+
----------
|
|
240
|
+
copy_all_attributes : bool
|
|
241
|
+
Default False, which writes only the elements the CT Image IOD requires.
|
|
242
|
+
|
|
243
|
+
Returns
|
|
244
|
+
-------
|
|
245
|
+
CTBuilder
|
|
246
|
+
self, so calls chain.
|
|
247
|
+
|
|
248
|
+
Notes
|
|
249
|
+
-----
|
|
250
|
+
Useful to inherit acquisition parameters -- KVP, exposure, convolution kernel --
|
|
251
|
+
that a fresh dataset would not carry. It also inherits everything else the source
|
|
252
|
+
had, including private tags and any burned-in identifiers, and those inherited
|
|
253
|
+
values now describe a volume they were not measured from. Geometry and pixel
|
|
254
|
+
elements are still overwritten from the volume.
|
|
255
|
+
"""
|
|
256
|
+
self.copy_all_attributes = copy_all_attributes
|
|
257
|
+
return self
|
|
258
|
+
|
|
259
|
+
def build(self) -> List[Dataset]:
|
|
260
|
+
"""
|
|
261
|
+
Slice the volume into a CT Image series.
|
|
262
|
+
|
|
263
|
+
Returns
|
|
264
|
+
-------
|
|
265
|
+
list[Dataset]
|
|
266
|
+
One dataset per slice, ordered along the slice normal.
|
|
267
|
+
|
|
268
|
+
Raises
|
|
269
|
+
------
|
|
270
|
+
ValueError
|
|
271
|
+
If no volume has been set.
|
|
272
|
+
"""
|
|
273
|
+
if self.volume_image is None:
|
|
274
|
+
raise ValueError("no volume set; call set_volume() before build()")
|
|
275
|
+
return self._build_series(
|
|
276
|
+
self.volume_image, self.plan_view, self.copy_all_attributes
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
def _generate_file_meta(self):
|
|
280
|
+
# https://dicom.nema.org/dicom/2013/output/chtml/part04/sect_i.4.html
|
|
281
|
+
# Group length is recomputed on write, so it is not set here.
|
|
282
|
+
file_meta = FileMetaDataset()
|
|
283
|
+
file_meta.FileMetaInformationVersion = b"\x00\x01"
|
|
284
|
+
file_meta.TransferSyntaxUID = ImplicitVRLittleEndian
|
|
285
|
+
file_meta.MediaStorageSOPClassUID = "1.2.840.10008.5.1.4.1.1.2"
|
|
286
|
+
file_meta.MediaStorageSOPInstanceUID = generate_uid(prefix=self.uid_prefix)
|
|
287
|
+
file_meta.ImplementationClassUID = self.uid_prefix + "1"
|
|
288
|
+
file_meta.ImplementationVersionName = "pydicomRT"
|
|
289
|
+
return file_meta
|
|
290
|
+
|
|
291
|
+
def _generate_base_dataset(self):
|
|
292
|
+
# Following the DICOM standard for CT Image
|
|
293
|
+
# https://dicom.innolitics.com/ciods/ct-image
|
|
294
|
+
file_meta = self._generate_file_meta()
|
|
295
|
+
ds = FileDataset(
|
|
296
|
+
self._base_file_name,
|
|
297
|
+
dataset={},
|
|
298
|
+
file_meta=file_meta,
|
|
299
|
+
preamble=b"\0" * 128,
|
|
300
|
+
)
|
|
301
|
+
ds = self._add_patient_information_from_ref_ds(ds, self.ref_ds)
|
|
302
|
+
ds = self._add_general_study_information(ds, self.ref_ds)
|
|
303
|
+
ds = self._add_general_series_information(ds, self.ref_ds)
|
|
304
|
+
ds = self._add_frame_of_reference_information(ds, self.ref_ds)
|
|
305
|
+
ds = self._add_general_equipment_information(ds, self.ref_ds)
|
|
306
|
+
ds = self._add_contrast_bolus_information(ds, self.ref_ds)
|
|
307
|
+
return ds
|
|
308
|
+
|
|
309
|
+
def _add_patient_information_from_ref_ds(self, ds: Dataset, ref_ds: Dataset):
|
|
310
|
+
ds.PatientID = getattr(ref_ds, "PatientID", "")
|
|
311
|
+
ds.PatientName = getattr(ref_ds, "PatientName", "")
|
|
312
|
+
ds.PatientBirthDate = getattr(ref_ds, "PatientBirthDate", "")
|
|
313
|
+
ds.PatientBirthTime = getattr(ref_ds, "PatientBirthTime", "")
|
|
314
|
+
ds.PatientSex = getattr(ref_ds, "PatientSex", "")
|
|
315
|
+
ds.PatientAge = getattr(ref_ds, "PatientAge", "")
|
|
316
|
+
ds.PatientWeight = getattr(ref_ds, "PatientWeight", "")
|
|
317
|
+
ds.PatientPosition = getattr(ref_ds, "PatientPosition", "")
|
|
318
|
+
return ds
|
|
319
|
+
|
|
320
|
+
def _add_general_study_information(self, ds: Dataset, ref_ds: Dataset):
|
|
321
|
+
ds.StudyInstanceUID = getattr(ref_ds, "StudyInstanceUID", "")
|
|
322
|
+
ds.StudyID = getattr(ref_ds, "StudyID", "")
|
|
323
|
+
ds.StudyDescription = getattr(ref_ds, "StudyDescription", "")
|
|
324
|
+
ds.StudyDate = getattr(ref_ds, "StudyDate", "")
|
|
325
|
+
ds.StudyTime = getattr(ref_ds, "StudyTime", "")
|
|
326
|
+
ds.AccessionNumber = getattr(ref_ds, "AccessionNumber", "")
|
|
327
|
+
ds.ReferringPhysicianName = getattr(ref_ds, "ReferringPhysicianName", "")
|
|
328
|
+
return ds
|
|
329
|
+
|
|
330
|
+
def _add_general_series_information(
|
|
331
|
+
self,
|
|
332
|
+
ds: Dataset,
|
|
333
|
+
ref_ds: Dataset,
|
|
334
|
+
series_number: str = "1",
|
|
335
|
+
series_desc_prefix: str = "CT"
|
|
336
|
+
):
|
|
337
|
+
dt = datetime.datetime.now()
|
|
338
|
+
ds.Modality = "CT"
|
|
339
|
+
ds.SpecificCharacterSet = "ISO_IR 192"
|
|
340
|
+
ds.SeriesInstanceUID = generate_uid(prefix=self.uid_prefix)
|
|
341
|
+
ds.SeriesNumber = series_number
|
|
342
|
+
ds.SeriesDescription = f"{series_desc_prefix} {dt.strftime('%Y%m%d%H%M')}"
|
|
343
|
+
ds.SeriesDate = dt.strftime("%Y%m%d")
|
|
344
|
+
ds.SeriesTime = dt.strftime("%H%M%S")
|
|
345
|
+
ds.ContentCreatorName = "pydicomRT"
|
|
346
|
+
ds.ProtocolName = getattr(ref_ds, "ProtocolName", "")
|
|
347
|
+
return ds
|
|
348
|
+
|
|
349
|
+
def _add_frame_of_reference_information(self, ds: Dataset, ref_ds: Dataset):
|
|
350
|
+
ds.FrameOfReferenceUID = getattr(ref_ds, "FrameOfReferenceUID", "")
|
|
351
|
+
ds.PositionReferenceIndicator = getattr(ref_ds, "PositionReferenceIndicator", "")
|
|
352
|
+
return ds
|
|
353
|
+
|
|
354
|
+
def _add_general_equipment_information(self, ds: Dataset, ref_ds: Dataset):
|
|
355
|
+
ds.Manufacturer = getattr(ref_ds, "Manufacturer", "pydicomRT")
|
|
356
|
+
ds.InstitutionName = getattr(ref_ds, "InstitutionName", "pydicomRT")
|
|
357
|
+
ds.InstitutionAddress = getattr(ref_ds, "InstitutionAddress", "")
|
|
358
|
+
ds.StationName = getattr(ref_ds, "StationName", "")
|
|
359
|
+
ds.InstitutionalDepartmentName = getattr(ref_ds, "InstitutionalDepartmentName", "")
|
|
360
|
+
ds.ManufacturerModelName = getattr(ref_ds, "ManufacturerModelName", "modelv1")
|
|
361
|
+
ds.DeviceSerialNumber = getattr(ref_ds, "DeviceSerialNumber", "")
|
|
362
|
+
ds.SoftwareVersions = getattr(ref_ds, "SoftwareVersions", "v1.0")
|
|
363
|
+
spatial_resolution = getattr(ref_ds, "SpatialResolution", None)
|
|
364
|
+
if spatial_resolution: ds.SpatialResolution = spatial_resolution
|
|
365
|
+
return ds
|
|
366
|
+
|
|
367
|
+
def _add_contrast_bolus_information(self, ds: Dataset, ref_ds: Dataset):
|
|
368
|
+
ds.ContrastBolusAgent = getattr(ref_ds, "ContrastBolusAgent", "")
|
|
369
|
+
return ds
|
|
370
|
+
|
|
371
|
+
def _build_series(
|
|
372
|
+
self,
|
|
373
|
+
sitk_image: sitk.Image,
|
|
374
|
+
plan_view: str,
|
|
375
|
+
copy_all_attributes: bool,
|
|
376
|
+
) -> List[Dataset]:
|
|
377
|
+
ds_list = []
|
|
378
|
+
|
|
379
|
+
now = datetime.datetime.now()
|
|
380
|
+
if copy_all_attributes:
|
|
381
|
+
base_ds = copy.deepcopy(self.template_ds)
|
|
382
|
+
base_ds.SeriesInstanceUID = generate_uid(prefix=self.uid_prefix)
|
|
383
|
+
else:
|
|
384
|
+
base_ds = self._generate_base_dataset()
|
|
385
|
+
base_ds.SOPClassUID = "1.2.840.10008.5.1.4.1.1.2"
|
|
386
|
+
base_ds.InstanceCreationDate = now.strftime("%Y%m%d")
|
|
387
|
+
|
|
388
|
+
base_ds.BitsAllocated = 16
|
|
389
|
+
base_ds.BitsStored = 16
|
|
390
|
+
base_ds.HighBit = 15
|
|
391
|
+
# The stored values below are unsigned; declaring them signed makes every value
|
|
392
|
+
# above 32767 read back negative.
|
|
393
|
+
base_ds.PixelRepresentation = 0
|
|
394
|
+
base_ds.PhotometricInterpretation = "MONOCHROME2"
|
|
395
|
+
base_ds.SamplesPerPixel = 1
|
|
396
|
+
# Air, expressed in the stored (pre-rescale) representation. VR is US here, so it is
|
|
397
|
+
# an integer -- it used to be written as raw bytes.
|
|
398
|
+
base_ds.PixelPaddingValue = 0
|
|
399
|
+
base_ds.ImageType = ["DERIVED", "SECONDARY", plan_view]
|
|
400
|
+
base_ds.KVP = getattr(self.ref_ds, "KVP", 120)
|
|
401
|
+
base_ds.AcquisitionNumber = getattr(self.ref_ds, "AcquisitionNumber", 1)
|
|
402
|
+
base_ds.ContentDate = now.strftime("%Y%m%d")
|
|
403
|
+
base_ds.ContentTime = now.strftime("%H%M%S")
|
|
404
|
+
base_ds.RescaleType = "HU"
|
|
405
|
+
|
|
406
|
+
column_axis, row_axis, normal_axis = PLANE_AXES[plan_view]
|
|
407
|
+
|
|
408
|
+
origin = np.array(sitk_image.GetOrigin(), dtype=float)
|
|
409
|
+
voxel_spacing = np.array(sitk_image.GetSpacing(), dtype=float)
|
|
410
|
+
# Column j of a SimpleITK direction matrix is the unit vector travelled when index
|
|
411
|
+
# axis j increases.
|
|
412
|
+
direction = np.array(sitk_image.GetDirection(), dtype=float).reshape(3, 3)
|
|
413
|
+
image_size = sitk_image.GetSize()
|
|
414
|
+
image_array = sitk.GetArrayFromImage(sitk_image)
|
|
415
|
+
|
|
416
|
+
slice_number = image_size[normal_axis]
|
|
417
|
+
rows = image_size[row_axis]
|
|
418
|
+
columns = image_size[column_axis]
|
|
419
|
+
|
|
420
|
+
# ImageOrientationPatient is the row direction (column index increasing) followed by
|
|
421
|
+
# the column direction (row index increasing).
|
|
422
|
+
image_orientation = (
|
|
423
|
+
direction[:, column_axis].tolist() + direction[:, row_axis].tolist()
|
|
424
|
+
)
|
|
425
|
+
# PixelSpacing is ordered [between rows, between columns] -- the reverse of the
|
|
426
|
+
# index order, which is why it is not simply (spacing[column], spacing[row]).
|
|
427
|
+
pixel_spacing = [float(voxel_spacing[row_axis]), float(voxel_spacing[column_axis])]
|
|
428
|
+
thickness = float(voxel_spacing[normal_axis])
|
|
429
|
+
slice_step = direction[:, normal_axis] * thickness
|
|
430
|
+
|
|
431
|
+
# image_array is (z, y, x); the SimpleITK axis n is numpy axis 2 - n.
|
|
432
|
+
numpy_slice_axis = 2 - normal_axis
|
|
433
|
+
|
|
434
|
+
for slice_idx in range(slice_number):
|
|
435
|
+
slice_ds = copy.deepcopy(base_ds)
|
|
436
|
+
slice_ds.InstanceCreationTime = datetime.datetime.now().strftime("%H%M%S.%f")
|
|
437
|
+
|
|
438
|
+
# Generate a new SOP Instance UID for each slice
|
|
439
|
+
instance_uid = generate_uid(prefix=self.uid_prefix)
|
|
440
|
+
slice_ds.file_meta.MediaStorageSOPInstanceUID = instance_uid
|
|
441
|
+
slice_ds.SOPInstanceUID = instance_uid
|
|
442
|
+
|
|
443
|
+
slice_2d = np.take(image_array, slice_idx, axis=numpy_slice_axis)
|
|
444
|
+
|
|
445
|
+
# Stored value = HU - RESCALE_INTERCEPT, clipped to what uint16 can hold. The
|
|
446
|
+
# upper bound used to be 65536 *before* adding the offset, which overflowed.
|
|
447
|
+
stored = np.clip(
|
|
448
|
+
slice_2d, RESCALE_INTERCEPT, _STORED_MAX + RESCALE_INTERCEPT
|
|
449
|
+
) - RESCALE_INTERCEPT
|
|
450
|
+
slice_ds.PixelData = np.rint(stored).astype(np.uint16).tobytes()
|
|
451
|
+
slice_ds.RescaleIntercept = RESCALE_INTERCEPT
|
|
452
|
+
slice_ds.RescaleSlope = 1
|
|
453
|
+
|
|
454
|
+
slice_ds.ImagePositionPatient = (origin + slice_idx * slice_step).tolist()
|
|
455
|
+
slice_ds.ImageOrientationPatient = image_orientation
|
|
456
|
+
slice_ds.PixelSpacing = pixel_spacing
|
|
457
|
+
slice_ds.SliceThickness = thickness
|
|
458
|
+
slice_ds.SpacingBetweenSlices = thickness
|
|
459
|
+
slice_ds.Rows = rows
|
|
460
|
+
slice_ds.Columns = columns
|
|
461
|
+
slice_ds.InstanceNumber = slice_idx + 1
|
|
462
|
+
ds_list.append(slice_ds)
|
|
463
|
+
|
|
464
|
+
return ds_list
|
pydicomrt/ct/check.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""IOD validation for CT Image."""
|
|
2
|
+
|
|
3
|
+
from pydicom.dataset import Dataset
|
|
4
|
+
|
|
5
|
+
from pydicomrt.utils.validate_dcm_info import build_check_result, check_iod
|
|
6
|
+
|
|
7
|
+
from .iod import CT_IMAGE_IOD
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def check_ct_iod(ct_ds: Dataset) -> dict:
|
|
11
|
+
"""
|
|
12
|
+
Validate a CT Image dataset against its CIOD.
|
|
13
|
+
|
|
14
|
+
Parameters
|
|
15
|
+
----------
|
|
16
|
+
ct_ds : Dataset
|
|
17
|
+
A single slice. CT is a single-frame IOD, so each slice is checked separately.
|
|
18
|
+
|
|
19
|
+
Returns
|
|
20
|
+
-------
|
|
21
|
+
dict
|
|
22
|
+
``{"result": bool, "content": list of str}``. ``result`` is True when conformant
|
|
23
|
+
and ``content`` empty; otherwise one message per missing or empty required
|
|
24
|
+
element.
|
|
25
|
+
|
|
26
|
+
See Also
|
|
27
|
+
--------
|
|
28
|
+
CTBuilder : Produces conformant slices.
|
|
29
|
+
|
|
30
|
+
Notes
|
|
31
|
+
-----
|
|
32
|
+
Structural conformance only. Check every slice, not just the first: pixel-data
|
|
33
|
+
elements are per-slice, so a series can pass on slice 0 and fail later.
|
|
34
|
+
|
|
35
|
+
Examples
|
|
36
|
+
--------
|
|
37
|
+
>>> slices = CTBuilder(reference_series).set_volume(image).build() # doctest: +SKIP
|
|
38
|
+
>>> bad = [i for i, s in enumerate(slices) # doctest: +SKIP
|
|
39
|
+
... if not check_ct_iod(s)["result"]]
|
|
40
|
+
"""
|
|
41
|
+
return build_check_result(check_iod(ds=ct_ds, config_map=CT_IMAGE_IOD))
|
pydicomrt/ct/iod.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from pydicom.uid import UID
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
CT_IMAGE_IOD = {
|
|
5
|
+
"PatientID": {},
|
|
6
|
+
"PatientName": {},
|
|
7
|
+
"PatientBirthDate": {},
|
|
8
|
+
"PatientSex": {},
|
|
9
|
+
"StudyInstanceUID": {},
|
|
10
|
+
"StudyID": {},
|
|
11
|
+
"StudyDate": {},
|
|
12
|
+
"StudyTime": {},
|
|
13
|
+
"AccessionNumber": {},
|
|
14
|
+
"SeriesInstanceUID": {"type": UID},
|
|
15
|
+
"SeriesNumber": {},
|
|
16
|
+
"Modality": {"value": "CT"},
|
|
17
|
+
"Manufacturer": {},
|
|
18
|
+
"FrameOfReferenceUID": {"type": UID},
|
|
19
|
+
"SOPClassUID": {"type": UID},
|
|
20
|
+
"SOPInstanceUID": {"type": UID},
|
|
21
|
+
"InstanceNumber": {},
|
|
22
|
+
|
|
23
|
+
"SliceThickness": {},
|
|
24
|
+
"ImagePositionPatient": {},
|
|
25
|
+
"ImageOrientationPatient": {},
|
|
26
|
+
"PixelSpacing": {},
|
|
27
|
+
|
|
28
|
+
"Rows": {},
|
|
29
|
+
"Columns": {},
|
|
30
|
+
|
|
31
|
+
"ImageType": {},
|
|
32
|
+
"BitsAllocated": {},
|
|
33
|
+
"BitsStored": {},
|
|
34
|
+
"HighBit": {},
|
|
35
|
+
"RescaleIntercept": {},
|
|
36
|
+
"RescaleSlope": {},
|
|
37
|
+
|
|
38
|
+
"PixelData": {},
|
|
39
|
+
|
|
40
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""RT Dose module"""
|
|
2
|
+
|
|
3
|
+
from .builder import (
|
|
4
|
+
RTDoseBuilder,
|
|
5
|
+
generate_base_dataset,
|
|
6
|
+
cp_information_from_ds,
|
|
7
|
+
add_dose_grid_to_ds,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
from .check import check_rtdose_iod
|
|
11
|
+
|
|
12
|
+
from .sitk_transform import (
|
|
13
|
+
get_dose_image,
|
|
14
|
+
get_dose_array,
|
|
15
|
+
get_dose_spacing,
|
|
16
|
+
get_dose_origin,
|
|
17
|
+
get_dose_direction,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
'RTDoseBuilder',
|
|
22
|
+
'generate_base_dataset',
|
|
23
|
+
'cp_information_from_ds',
|
|
24
|
+
'add_dose_grid_to_ds',
|
|
25
|
+
'check_rtdose_iod',
|
|
26
|
+
|
|
27
|
+
'get_dose_image',
|
|
28
|
+
'get_dose_array',
|
|
29
|
+
'get_dose_spacing',
|
|
30
|
+
'get_dose_origin',
|
|
31
|
+
'get_dose_direction',
|
|
32
|
+
]
|