dbdicom 0.2.6__py3-none-any.whl → 0.3.1__py3-none-any.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.

Potentially problematic release.


This version of dbdicom might be problematic. Click here for more details.

Files changed (52) hide show
  1. dbdicom/__init__.py +1 -28
  2. dbdicom/api.py +287 -0
  3. dbdicom/const.py +144 -0
  4. dbdicom/dataset.py +721 -0
  5. dbdicom/dbd.py +736 -0
  6. dbdicom/external/__pycache__/__init__.cpython-311.pyc +0 -0
  7. dbdicom/external/dcm4che/__pycache__/__init__.cpython-311.pyc +0 -0
  8. dbdicom/external/dcm4che/bin/__pycache__/__init__.cpython-311.pyc +0 -0
  9. dbdicom/register.py +527 -0
  10. dbdicom/{ds/types → sop_classes}/ct_image.py +2 -16
  11. dbdicom/{ds/types → sop_classes}/enhanced_mr_image.py +153 -26
  12. dbdicom/{ds/types → sop_classes}/mr_image.py +185 -140
  13. dbdicom/sop_classes/parametric_map.py +310 -0
  14. dbdicom/sop_classes/secondary_capture.py +140 -0
  15. dbdicom/sop_classes/segmentation.py +311 -0
  16. dbdicom/{ds/types → sop_classes}/ultrasound_multiframe_image.py +1 -15
  17. dbdicom/{ds/types → sop_classes}/xray_angiographic_image.py +2 -17
  18. dbdicom/utils/arrays.py +36 -0
  19. dbdicom/utils/files.py +0 -20
  20. dbdicom/utils/image.py +10 -629
  21. dbdicom-0.3.1.dist-info/METADATA +28 -0
  22. dbdicom-0.3.1.dist-info/RECORD +53 -0
  23. dbdicom/create.py +0 -457
  24. dbdicom/dro.py +0 -174
  25. dbdicom/ds/__init__.py +0 -10
  26. dbdicom/ds/create.py +0 -63
  27. dbdicom/ds/dataset.py +0 -869
  28. dbdicom/ds/dictionaries.py +0 -620
  29. dbdicom/ds/types/parametric_map.py +0 -226
  30. dbdicom/extensions/__init__.py +0 -9
  31. dbdicom/extensions/dipy.py +0 -448
  32. dbdicom/extensions/elastix.py +0 -503
  33. dbdicom/extensions/matplotlib.py +0 -107
  34. dbdicom/extensions/numpy.py +0 -271
  35. dbdicom/extensions/scipy.py +0 -1512
  36. dbdicom/extensions/skimage.py +0 -1030
  37. dbdicom/extensions/sklearn.py +0 -243
  38. dbdicom/extensions/vreg.py +0 -1390
  39. dbdicom/manager.py +0 -2132
  40. dbdicom/message.py +0 -119
  41. dbdicom/pipelines.py +0 -66
  42. dbdicom/record.py +0 -1893
  43. dbdicom/types/database.py +0 -107
  44. dbdicom/types/instance.py +0 -231
  45. dbdicom/types/patient.py +0 -40
  46. dbdicom/types/series.py +0 -2874
  47. dbdicom/types/study.py +0 -58
  48. dbdicom-0.2.6.dist-info/METADATA +0 -72
  49. dbdicom-0.2.6.dist-info/RECORD +0 -66
  50. {dbdicom-0.2.6.dist-info → dbdicom-0.3.1.dist-info}/WHEEL +0 -0
  51. {dbdicom-0.2.6.dist-info → dbdicom-0.3.1.dist-info}/licenses/LICENSE +0 -0
  52. {dbdicom-0.2.6.dist-info → dbdicom-0.3.1.dist-info}/top_level.txt +0 -0
dbdicom/dataset.py ADDED
@@ -0,0 +1,721 @@
1
+ # Test data
2
+ # https://www.aliza-dicom-viewer.com/download/datasets
3
+
4
+ import os
5
+ from datetime import datetime
6
+ import struct
7
+ from tqdm import tqdm
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+ import pydicom
12
+ from pydicom.util.codify import code_file
13
+ import pydicom.config
14
+ from pydicom.dataset import Dataset
15
+ import vreg
16
+
17
+ import dbdicom.utils.image as image
18
+ import dbdicom.utils.variables as variables
19
+ from dbdicom.sop_classes import (
20
+ xray_angiographic_image,
21
+ ct_image,
22
+ mr_image,
23
+ enhanced_mr_image,
24
+ ultrasound_multiframe_image,
25
+ parametric_map,
26
+ segmentation,
27
+ )
28
+
29
+
30
+ # This ensures that dates and times are read as TM, DT and DA classes
31
+ pydicom.config.datetime_conversion = True
32
+
33
+
34
+ SOPCLASS = {
35
+ '1.2.840.10008.5.1.4.1.1.4': 'MRImage',
36
+ '1.2.840.10008.5.1.4.1.1.4.1': 'EnhancedMRImage',
37
+ '1.2.840.10008.5.1.4.1.1.2': 'CTImage',
38
+ '1.2.840.10008.5.1.4.1.1.12.2': 'XrayAngiographicImage',
39
+ '1.2.840.10008.5.1.4.1.1.3.1': 'UltrasoundMultiFrameImage',
40
+ '1.2.840.10008.5.1.4.1.1.30': 'ParametricMap',
41
+ '1.2.840.10008.5.1.4.1.1.66.4': 'Segmentation',
42
+ }
43
+ SOPCLASSMODULE = {
44
+ '1.2.840.10008.5.1.4.1.1.4': mr_image,
45
+ '1.2.840.10008.5.1.4.1.1.4.1': enhanced_mr_image,
46
+ '1.2.840.10008.5.1.4.1.1.2': ct_image,
47
+ '1.2.840.10008.5.1.4.1.1.12.2': xray_angiographic_image,
48
+ '1.2.840.10008.5.1.4.1.1.3.1': ultrasound_multiframe_image,
49
+ '1.2.840.10008.5.1.4.1.1.30': parametric_map,
50
+ '1.2.840.10008.5.1.4.1.1.66.4': segmentation,
51
+ }
52
+
53
+
54
+ def read_dataset(file):
55
+
56
+ try:
57
+ ds = pydicom.dcmread(file)
58
+ # ds = pydicom.dcmread(file, force=True) # more robust but hides corrupted data
59
+ except Exception:
60
+ raise FileNotFoundError('File not found')
61
+
62
+ return ds
63
+
64
+
65
+ def new_dataset(sop_class):
66
+
67
+ if sop_class == 'MRImage':
68
+ return mr_image.default()
69
+ if sop_class == 'EnhancedMRImage':
70
+ return enhanced_mr_image.default()
71
+ if sop_class == 'CTImage':
72
+ return ct_image.default()
73
+ if sop_class == 'XrayAngiographicImage':
74
+ return xray_angiographic_image.default()
75
+ if sop_class == 'UltrasoundMultiFrameImage':
76
+ return ultrasound_multiframe_image.default()
77
+ else:
78
+ raise ValueError(
79
+ f"DICOM class {sop_class} is not currently supported"
80
+ )
81
+
82
+
83
+
84
+ def get_values(ds, tags):
85
+ """Return a list of values for a dataset"""
86
+
87
+ # https://pydicom.github.io/pydicom/stable/guides/element_value_types.html
88
+ if np.isscalar(tags):
89
+ return get_values(ds, [tags])[0]
90
+
91
+ row = []
92
+ for tag in tags:
93
+ value = None
94
+
95
+ # If the tag is provided as string
96
+ if isinstance(tag, str):
97
+ if hasattr(ds, tag):
98
+ pydcm_value = ds[tag].value
99
+ try:
100
+ VR = pydicom.datadict.dictionary_VR(tag)
101
+ except:
102
+ VR = None
103
+ value = to_set_type(pydcm_value, VR) # ELIMINATE THIS STEP - return pydicom datatypes
104
+
105
+ # If the tag is a tuple of hexadecimal values
106
+ else:
107
+ if tag in ds:
108
+ try:
109
+ VR = pydicom.datadict.dictionary_VR(tag)
110
+ except:
111
+ VR = None
112
+ value = to_set_type(ds[tag].value, VR)
113
+
114
+ # If a tag is not present in the dataset, check if it can be derived
115
+ if value is None:
116
+ value = derive_data_element(ds, tag)
117
+
118
+ row.append(value)
119
+ return row
120
+
121
+
122
+ def set_values(ds, tags, values, VR=None, coords=None):
123
+
124
+ if np.isscalar(tags):
125
+ tags = [tags]
126
+ values = [values]
127
+ VR = [VR]
128
+ elif VR is None:
129
+ VR = [None] * len(tags)
130
+
131
+ if coords is not None:
132
+ tags += list(coords.keys())
133
+ values += list(coords.values())
134
+
135
+ for i, tag in enumerate(tags):
136
+
137
+ if values[i] is None:
138
+ if isinstance(tag, str):
139
+ if hasattr(ds, tag):
140
+ del ds[tag]
141
+ else: # hexadecimal tuple
142
+ if tag in ds:
143
+ del ds[tag]
144
+
145
+ elif isinstance(tag, str):
146
+ if hasattr(ds, tag):
147
+ ds[tag].value = format_value(values[i], tag=tag)
148
+ else:
149
+ _add_new(ds, tag, values[i], VR=VR[i])
150
+
151
+ else: # hexadecimal tuple
152
+ if tag in ds:
153
+ ds[tag].value = format_value(values[i], tag=tag)
154
+ else:
155
+ _add_new(ds, tag, values[i], VR=VR[i])
156
+
157
+ #_set_derived_data_element(ds, tag, values[i])
158
+
159
+ return ds
160
+
161
+
162
+
163
+ def value(ds, tags):
164
+ # Same as get_values but without VR lookup
165
+
166
+ # https://pydicom.github.io/pydicom/stable/guides/element_value_types.html
167
+ if np.isscalar(tags):
168
+ return get_values(ds, [tags])[0]
169
+
170
+ row = []
171
+ for tag in tags:
172
+ value = None
173
+
174
+ # If the tag is provided as string
175
+ if isinstance(tag, str):
176
+
177
+ if hasattr(ds, tag):
178
+ value = to_set_type(ds[tag].value)
179
+
180
+ # If the tag is a tuple of hexadecimal values
181
+ else:
182
+ if tag in ds:
183
+ value = to_set_type(ds[tag].value)
184
+
185
+ # If a tag is not present in the dataset, check if it can be derived
186
+ if value is None:
187
+ value = derive_data_element(ds, tag)
188
+
189
+ row.append(value)
190
+ return row
191
+
192
+
193
+ def set_value(ds, tags, values):
194
+ # Same as set_values but without VR lookup
195
+ # This excludes new private tags - set those using add_private()
196
+ if np.isscalar(tags):
197
+ tags = [tags]
198
+ values = [values]
199
+
200
+ for i, tag in enumerate(tags):
201
+
202
+ if values[i] is None:
203
+ if isinstance(tag, str):
204
+ if hasattr(ds, tag):
205
+ del ds[tag]
206
+ else: # hexadecimal tuple
207
+ if tag in ds:
208
+ del ds[tag]
209
+
210
+ elif isinstance(tag, str):
211
+ if hasattr(ds, tag):
212
+ ds[tag].value = check_value(values[i], tag)
213
+ else:
214
+ add_new(ds, tag, values[i])
215
+
216
+ else: # hexadecimal tuple
217
+ if tag in ds:
218
+ ds[tag].value = check_value(values[i], tag)
219
+ else:
220
+ add_new(ds, tag, values[i])
221
+
222
+ return ds
223
+
224
+
225
+
226
+ def write(ds, file, status=None):
227
+ # check if directory exists and create it if not
228
+ dir = os.path.dirname(file)
229
+ if not os.path.exists(dir):
230
+ os.makedirs(dir)
231
+ ds.save_as(file, write_like_original=False)
232
+
233
+
234
+ def codify(source_file, save_file, **kwargs):
235
+ str = code_file(source_file, **kwargs)
236
+ file = open(save_file, "w")
237
+ file.write(str)
238
+ file.close()
239
+
240
+
241
+ def read_data(files, tags, path=None, images_only=False):
242
+
243
+ if np.isscalar(files):
244
+ files = [files]
245
+ if np.isscalar(tags):
246
+ tags = [tags]
247
+ dict = {}
248
+ for i, file in tqdm(enumerate(files), 'reading files..'):
249
+ try:
250
+ ds = pydicom.dcmread(file, force=True, specific_tags=tags+['Rows'])
251
+ except:
252
+ pass
253
+ else:
254
+ if isinstance(ds, pydicom.dataset.FileDataset):
255
+ if 'TransferSyntaxUID' in ds.file_meta:
256
+ if images_only:
257
+ if not 'Rows' in ds:
258
+ continue
259
+ row = get_values(ds, tags)
260
+ if path is None:
261
+ index = file
262
+ else:
263
+ index = os.path.relpath(file, path)
264
+ dict[index] = row
265
+ return dict
266
+
267
+
268
+
269
+ def read_dataframe(files, tags, path=None, images_only=False):
270
+ if np.isscalar(files):
271
+ files = [files]
272
+ if np.isscalar(tags):
273
+ tags = [tags]
274
+ array = []
275
+ dicom_files = []
276
+ for i, file in tqdm(enumerate(files), desc='Reading DICOM folder'):
277
+ try:
278
+ ds = pydicom.dcmread(file, force=True, specific_tags=tags+['Rows'])
279
+ except:
280
+ pass
281
+ else:
282
+ if isinstance(ds, pydicom.dataset.FileDataset):
283
+ if 'TransferSyntaxUID' in ds.file_meta:
284
+ if images_only:
285
+ if not 'Rows' in ds:
286
+ continue
287
+ row = get_values(ds, tags)
288
+ array.append(row)
289
+ if path is None:
290
+ index = file
291
+ else:
292
+ index = os.path.relpath(file, path)
293
+ dicom_files.append(index)
294
+ df = pd.DataFrame(array, index = dicom_files, columns = tags)
295
+ return df
296
+
297
+
298
+ def _add_new(ds, tag, value, VR='OW'):
299
+ if not isinstance(tag, pydicom.tag.BaseTag):
300
+ tag = pydicom.tag.Tag(tag)
301
+ if not tag.is_private: # Add a new data element
302
+ value_repr = pydicom.datadict.dictionary_VR(tag)
303
+ if value_repr == 'US or SS':
304
+ if value >= 0:
305
+ value_repr = 'US'
306
+ else:
307
+ value_repr = 'SS'
308
+ elif value_repr == 'OB or OW':
309
+ value_repr = 'OW'
310
+ ds.add_new(tag, value_repr, format_value(value, value_repr))
311
+ else:
312
+ if (tag.group, 0x0010) not in ds:
313
+ ds.private_block(tag.group, 'dbdicom ' + str(tag.group), create=True)
314
+ ds.add_new(tag, VR, format_value(value, VR))
315
+
316
+
317
+ def add_new(ds, tag, value):
318
+ if not isinstance(tag, pydicom.tag.BaseTag):
319
+ tag = pydicom.tag.Tag(tag)
320
+ if tag.is_private:
321
+ raise ValueError("if you want to add a private data element, use "
322
+ "dataset.add_private()")
323
+ # Add a new data element
324
+ value_repr = pydicom.datadict.dictionary_VR(tag)
325
+ if value_repr == 'US or SS':
326
+ if value >= 0:
327
+ value_repr = 'US'
328
+ else:
329
+ value_repr = 'SS'
330
+ elif value_repr == 'OB or OW':
331
+ value_repr = 'OW'
332
+ ds.add_new(tag, value_repr, format_value(value, value_repr))
333
+
334
+
335
+
336
+ def add_private(ds, tag, value, VR):
337
+ if not isinstance(tag, pydicom.tag.BaseTag):
338
+ tag = pydicom.tag.Tag(tag)
339
+ if (tag.group, 0x0010) not in ds:
340
+ ds.private_block(tag.group, 'dbdicom ' + str(tag.group), create=True)
341
+ ds.add_new(tag, VR, format_value(value, VR))
342
+
343
+
344
+ def derive_data_element(ds, tag):
345
+ """Tags that are not required but can be derived from other required tags"""
346
+
347
+ if tag == 'SliceLocation' or tag == (0x0020, 0x1041):
348
+ if 'ImageOrientationPatient' in ds and 'ImagePositionPatient' in ds:
349
+ return image.slice_location(
350
+ ds['ImageOrientationPatient'].value,
351
+ ds['ImagePositionPatient'].value,
352
+ )
353
+ # To be extended ad hoc with other tags that can be derived
354
+
355
+
356
+
357
+ def format_value(value, VR=None, tag=None):
358
+
359
+ # If the change below is made (TM, DA, DT) then this needs to
360
+ # convert those to string before setting
361
+
362
+ # Slow - dictionary lookup for every value write
363
+
364
+ if VR is None:
365
+ VR = pydicom.datadict.dictionary_VR(tag)
366
+
367
+ if VR == 'LO':
368
+ if len(value) > 64:
369
+ return value[-64:]
370
+ #return value[:64]
371
+ if VR == 'TM':
372
+ return variables.seconds_to_str(value)
373
+
374
+ return value
375
+
376
+
377
+ def check_value(value, tag):
378
+
379
+ # If the change below is made (TM, DA, DT) then this needs to
380
+ # convert those to string before setting
381
+
382
+ LO = [
383
+ 'SeriesDescription',
384
+ 'StudyDescription',
385
+ ]
386
+ TM = [
387
+ 'AcquisitionTime',
388
+ ]
389
+
390
+ if tag in LO:
391
+ if len(value) > 64:
392
+ return value[-64:]
393
+ if tag in TM:
394
+ return variables.seconds_to_str(value)
395
+
396
+ return value
397
+
398
+
399
+ def to_set_type(value, VR=None):
400
+ """
401
+ Convert pydicom datatypes to the python datatypes used to set the parameter.
402
+ """
403
+ # Not a good idea to modify pydicom set/get values. confusing and requires extra VR lookups
404
+
405
+ if VR == 'TM':
406
+ # pydicom sometimes returns string values for TM data types
407
+ if isinstance(value, str):
408
+ return variables.str_to_seconds(value)
409
+
410
+ if value.__class__.__name__ == 'MultiValue':
411
+ return [to_set_type(v, VR) for v in value]
412
+ if value.__class__.__name__ == 'PersonName':
413
+ return str(value)
414
+ if value.__class__.__name__ == 'Sequence':
415
+ return [ds for ds in value]
416
+ if value.__class__.__name__ == 'TM':
417
+ return variables.time_to_seconds(value) # return datetime.time
418
+ if value.__class__.__name__ == 'UID':
419
+ return str(value)
420
+ if value.__class__.__name__ == 'IS':
421
+ return int(value)
422
+ if value.__class__.__name__ == 'DT':
423
+ return variables.datetime_to_str(value) # return datetime.datetime
424
+ if value.__class__.__name__ == 'DA': # return datetime.date
425
+ return variables.date_to_str(value)
426
+ if value.__class__.__name__ == 'DSfloat':
427
+ return float(value)
428
+ if value.__class__.__name__ == 'DSdecimal':
429
+ return int(value)
430
+
431
+ return value
432
+
433
+
434
+ def new_uid(n=None):
435
+
436
+ if n is None:
437
+ return pydicom.uid.generate_uid()
438
+ else:
439
+ return [pydicom.uid.generate_uid() for _ in range(n)]
440
+
441
+
442
+
443
+
444
+ def window(ds):
445
+ """Centre and width of the pixel data after applying rescale slope and intercept"""
446
+
447
+ if 'WindowCenter' in ds:
448
+ centre = ds.WindowCenter
449
+ if 'WindowWidth' in ds:
450
+ width = ds.WindowWidth
451
+ if centre is None or width is None:
452
+ array = pixel_data(ds)
453
+ #p = np.percentile(array, [25, 50, 75])
454
+ min = np.min(array)
455
+ max = np.max(array)
456
+ if centre is None:
457
+ centre = (max+min)/2
458
+ #centre = p[1]
459
+ if width is None:
460
+ width = 0.9*(max-min)
461
+ #width = p[2] - p[0]
462
+ return centre, width
463
+
464
+ def set_window(ds, center, width):
465
+ ds.WindowCenter = center
466
+ ds.WindowWidth = width
467
+
468
+ # List of all supported (matplotlib) colormaps
469
+
470
+ COLORMAPS = ['cividis', 'magma', 'plasma', 'viridis',
471
+ 'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
472
+ 'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
473
+ 'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn',
474
+ 'binary', 'gist_yarg', 'gist_gray', 'bone', 'pink',
475
+ 'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia',
476
+ 'hot', 'afmhot', 'gist_heat', 'copper',
477
+ 'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',
478
+ 'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic',
479
+ 'twilight', 'twilight_shifted', 'hsv',
480
+ 'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern',
481
+ 'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg', 'turbo',
482
+ 'gist_rainbow', 'rainbow', 'jet', 'nipy_spectral', 'gist_ncar']
483
+
484
+ # Include support for DICOM natiove colormaps (see pydicom guide on working with pixel data)
485
+
486
+
487
+ def lut(ds):
488
+ """Return RGB as float with values in [0,1]"""
489
+
490
+ if 'PhotometricInterpretation' not in ds:
491
+ return None
492
+ if ds.PhotometricInterpretation != 'PALETTE COLOR':
493
+ return None
494
+
495
+ if ds.BitsAllocated == 8:
496
+ dtype = np.ubyte
497
+ elif ds.BitsAllocated == 16:
498
+ dtype = np.uint16
499
+
500
+ R = ds.RedPaletteColorLookupTableData
501
+ G = ds.GreenPaletteColorLookupTableData
502
+ B = ds.BluePaletteColorLookupTableData
503
+
504
+ R = np.frombuffer(R, dtype=dtype)
505
+ G = np.frombuffer(G, dtype=dtype)
506
+ B = np.frombuffer(B, dtype=dtype)
507
+
508
+ R = R.astype(np.float32)
509
+ G = G.astype(np.float32)
510
+ B = B.astype(np.float32)
511
+
512
+ R *= 1.0/(np.power(2, ds.RedPaletteColorLookupTableDescriptor[2]) - 1)
513
+ G *= 1.0/(np.power(2, ds.GreenPaletteColorLookupTableDescriptor[2]) - 1)
514
+ B *= 1.0/(np.power(2, ds.BluePaletteColorLookupTableDescriptor[2]) - 1)
515
+
516
+ return np.transpose([R, G, B])
517
+
518
+
519
+ def set_lut(ds, RGB):
520
+ """Set RGB as float with values in range [0,1]"""
521
+
522
+ ds.PhotometricInterpretation = 'PALETTE COLOR'
523
+
524
+ RGB *= (np.power(2, ds.BitsAllocated) - 1)
525
+
526
+ if ds.BitsAllocated == 8:
527
+ RGB = RGB.astype(np.ubyte)
528
+ elif ds.BitsAllocated == 16:
529
+ RGB = RGB.astype(np.uint16)
530
+
531
+ # Define the properties of the LUT
532
+ ds.add_new('0x00281101', 'US', [255, 0, ds.BitsAllocated])
533
+ ds.add_new('0x00281102', 'US', [255, 0, ds.BitsAllocated])
534
+ ds.add_new('0x00281103', 'US', [255, 0, ds.BitsAllocated])
535
+
536
+ # Scale the colorsList to the available range
537
+ ds.RedPaletteColorLookupTableData = bytes(RGB[:,0])
538
+ ds.GreenPaletteColorLookupTableData = bytes(RGB[:,1])
539
+ ds.BluePaletteColorLookupTableData = bytes(RGB[:,2])
540
+
541
+
542
+
543
+ def affine(ds, multislice=False):
544
+ if multislice:
545
+ return image.affine_matrix(
546
+ get_values(ds, 'ImageOrientationPatient'),
547
+ get_values(ds, 'ImagePositionPatient'),
548
+ get_values(ds, 'PixelSpacing'),
549
+ get_values(ds, 'SpacingBetweenSlices'),
550
+ )
551
+ else:
552
+ return image.affine_matrix(
553
+ get_values(ds, 'ImageOrientationPatient'),
554
+ get_values(ds, 'ImagePositionPatient'),
555
+ get_values(ds, 'PixelSpacing'),
556
+ get_values(ds, 'SliceThickness'),
557
+ )
558
+
559
+
560
+ def set_affine(ds, affine, multislice=False):
561
+ if affine is None:
562
+ raise ValueError('The affine cannot be set to an empty value')
563
+ v = image.dismantle_affine_matrix(affine)
564
+ set_values(ds, 'PixelSpacing', v['PixelSpacing'])
565
+ if multislice:
566
+ set_values(ds, 'SpacingBetweenSlices', v['SliceThickness'])
567
+ else:
568
+ set_values(ds, 'SliceThickness', v['SliceThickness'])
569
+ set_values(ds, 'ImageOrientationPatient', v['ImageOrientationPatient'])
570
+ set_values(ds, 'ImagePositionPatient', v['ImagePositionPatient'])
571
+ set_values(ds, 'SliceLocation', np.dot(v['ImagePositionPatient'], v['slice_cosine']))
572
+
573
+
574
+
575
+ def pixel_data(ds):
576
+
577
+ try:
578
+ mod = SOPCLASSMODULE[ds.SOPClassUID]
579
+ except KeyError:
580
+ raise ValueError(
581
+ f"DICOM class {ds.SOPClassUID} is not currently supported."
582
+ )
583
+ if hasattr(mod, 'pixel_data'):
584
+ return getattr(mod, 'pixel_data')(ds)
585
+
586
+ try:
587
+ array = ds.pixel_array
588
+ except:
589
+ return None
590
+ array = array.astype(np.float32)
591
+ slope = float(getattr(ds, 'RescaleSlope', 1))
592
+ intercept = float(getattr(ds, 'RescaleIntercept', 0))
593
+ array *= slope
594
+ array += intercept
595
+ return np.transpose(array)
596
+
597
+
598
+ def set_pixel_data(ds, array, value_range=None):
599
+ if array is None:
600
+ raise ValueError('The pixel array cannot be set to an empty value.')
601
+
602
+ try:
603
+ mod = SOPCLASSMODULE[ds.SOPClassUID]
604
+ except KeyError:
605
+ raise ValueError(
606
+ f"DICOM class {ds.SOPClassUID} is not currently supported."
607
+ )
608
+ if hasattr(mod, 'set_pixel_data'):
609
+ return getattr(mod, 'set_pixel_data')(ds, array)
610
+
611
+ # if array.ndim >= 3: # remove spurious dimensions of 1
612
+ # array = np.squeeze(array)
613
+
614
+ array = image.clip(array.astype(np.float32), value_range=value_range)
615
+ array, slope, intercept = image.scale_to_range(array, ds.BitsAllocated)
616
+ array = np.transpose(array)
617
+
618
+ ds.PixelRepresentation = 0
619
+ #ds.SmallestImagePixelValue = int(0)
620
+ #ds.LargestImagePixelValue = int(2**ds.BitsAllocated - 1)
621
+ #ds.set_values('SmallestImagePixelValue', int(0))
622
+ #ds.set_values('LargestImagePixelValue', int(2**ds.BitsAllocated - 1))
623
+ ds.RescaleSlope = 1 / slope
624
+ ds.RescaleIntercept = - intercept / slope
625
+ # ds.WindowCenter = (maximum + minimum) / 2
626
+ # ds.WindowWidth = maximum - minimum
627
+ ds.Rows = array.shape[0]
628
+ ds.Columns = array.shape[1]
629
+ ds.PixelData = array.tobytes()
630
+
631
+
632
+ def volume(ds, multislice=False):
633
+ return vreg.volume(pixel_data(ds), affine(ds, multislice))
634
+
635
+ def set_volume(ds, volume:vreg.Volume3D, multislice=False):
636
+ if volume is None:
637
+ raise ValueError('The volume cannot be set to an empty value.')
638
+ image = np.squeeze(volume.values)
639
+ if image.ndim != 2:
640
+ raise ValueError("Can only write 2D images to a dataset.")
641
+ set_pixel_data(ds, image)
642
+ set_affine(ds, volume.affine, multislice)
643
+ if volume.coords is not None:
644
+ # All other dimensions should have size 1
645
+ coords = volume.coords.reshape((volume.coords.shape[0], -1))
646
+ for i, d in enumerate(volume.dims):
647
+ try:
648
+ set_values(ds, d, coords[i,0])
649
+ except KeyError:
650
+ raise ValueError(
651
+ "Cannot write volume to DICOM. "
652
+ f"Volume dimension {d} is not a recognized DICOM data-element. "
653
+ f"Use Volume3D.set_dims() with proper DICOM keywords "
654
+ "or (group, element) tags to change the dimensions."
655
+ )
656
+
657
+
658
+ def image_type(ds):
659
+ """Determine if an image is Magnitude, Phase, Real or Imaginary image or None"""
660
+
661
+ if (0x0043, 0x102f) in ds:
662
+ private_ge = ds[0x0043, 0x102f]
663
+ try:
664
+ value = struct.unpack('h', private_ge.value)[0]
665
+ except:
666
+ value = private_ge.value
667
+ if value == 0:
668
+ return 'MAGNITUDE'
669
+ if value == 1:
670
+ return 'PHASE'
671
+ if value == 2:
672
+ return 'REAL'
673
+ if value == 3:
674
+ return 'IMAGINARY'
675
+
676
+ if 'ImageType' in ds:
677
+ type = set(ds.ImageType)
678
+ if set(['M', 'MAGNITUDE']).intersection(type):
679
+ return 'MAGNITUDE'
680
+ if set(['P', 'PHASE']).intersection(type):
681
+ return 'PHASE'
682
+ if set(['R', 'REAL']).intersection(type):
683
+ return 'REAL'
684
+ if set(['I', 'IMAGINARY']).intersection(type):
685
+ return 'IMAGINARY'
686
+
687
+ if 'ComplexImageComponent' in ds:
688
+ return ds.ComplexImageComponent
689
+
690
+ return 'UNKNOWN'
691
+
692
+
693
+ def set_image_type(ds, value):
694
+ ds.ImageType = value
695
+
696
+
697
+ def signal_type(ds):
698
+ """Determine if an image is Water, Fat, In-Phase, Out-phase image or None"""
699
+
700
+ if hasattr(ds, 'ImageType'):
701
+ type = set(ds.ImageType)
702
+ if set(['W', 'WATER']).intersection(type):
703
+ return 'WATER'
704
+ elif set(['F', 'FAT']).intersection(type):
705
+ return 'FAT'
706
+ elif set(['IP', 'IN_PHASE']).intersection(type):
707
+ return 'IN_PHASE'
708
+ elif set(['OP', 'OUT_PHASE']).intersection(type):
709
+ return 'OP_PHASE'
710
+ return 'UNKNOWN'
711
+
712
+
713
+ def set_signal_type(ds, value):
714
+ ds.ImageType = value
715
+
716
+
717
+
718
+ if __name__=='__main__':
719
+
720
+ pass
721
+ #codify('C:\\Users\\md1spsx\\Documents\\f32bit.dcm', 'C:\\Users\\md1spsx\\Documents\\f32bit.py')