Debian Codegraph @

imageio/plugins/_dicom.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # imageio is distributed under the terms of the (new) BSD License.
3
4 """Plugin for reading DICOM files."""
5
6 # todo: Use pydicom:
7 # * Note: is not py3k ready yet
8 # * Allow reading the full meta info
9 # I think we can more or less replace the SimpleDicomReader with a
10 # pydicom.Dataset For series, only ned to read the full info from one
11 # file: speed still high
12 # * Perhaps allow writing?
13
14 import sys
15 import os
16 import struct
17 import logging
18
19 import numpy as np
20
21 logger = logging.getLogger(__name__)
22
23 # Determine endianity of system
24 sys_is_little_endian = sys.byteorder == "little"
25
26 # Define a dictionary that contains the tags that we would like to know
27 MINIDICT = {
28 (0x7FE0, 0x0010): ("PixelData", "OB"),
29 # Date and time
30 (0x0008, 0x0020): ("StudyDate", "DA"),
31 (0x0008, 0x0021): ("SeriesDate", "DA"),
32 (0x0008, 0x0022): ("AcquisitionDate", "DA"),
33 (0x0008, 0x0023): ("ContentDate", "DA"),
34 (0x0008, 0x0030): ("StudyTime", "TM"),
35 (0x0008, 0x0031): ("SeriesTime", "TM"),
36 (0x0008, 0x0032): ("AcquisitionTime", "TM"),
37 (0x0008, 0x0033): ("ContentTime", "TM"),
38 # With what, where, by whom?
39 (0x0008, 0x0060): ("Modality", "CS"),
40 (0x0008, 0x0070): ("Manufacturer", "LO"),
41 (0x0008, 0x0080): ("InstitutionName", "LO"),
42 # Descriptions
43 (0x0008, 0x1030): ("StudyDescription", "LO"),
44 (0x0008, 0x103E): ("SeriesDescription", "LO"),
45 # UID's
46 (0x0008, 0x0016): ("SOPClassUID", "UI"),
47 (0x0008, 0x0018): ("SOPInstanceUID", "UI"),
48 (0x0020, 0x000D): ("StudyInstanceUID", "UI"),
49 (0x0020, 0x000E): ("SeriesInstanceUID", "UI"),
50 (0x0008, 0x0117): ("ContextUID", "UI"),
51 # Numbers
52 (0x0020, 0x0011): ("SeriesNumber", "IS"),
53 (0x0020, 0x0012): ("AcquisitionNumber", "IS"),
54 (0x0020, 0x0013): ("InstanceNumber", "IS"),
55 (0x0020, 0x0014): ("IsotopeNumber", "IS"),
56 (0x0020, 0x0015): ("PhaseNumber", "IS"),
57 (0x0020, 0x0016): ("IntervalNumber", "IS"),
58 (0x0020, 0x0017): ("TimeSlotNumber", "IS"),
59 (0x0020, 0x0018): ("AngleNumber", "IS"),
60 (0x0020, 0x0019): ("ItemNumber", "IS"),
61 (0x0020, 0x0020): ("PatientOrientation", "CS"),
62 (0x0020, 0x0030): ("ImagePosition", "CS"),
63 (0x0020, 0x0032): ("ImagePositionPatient", "CS"),
64 (0x0020, 0x0035): ("ImageOrientation", "CS"),
65 (0x0020, 0x0037): ("ImageOrientationPatient", "CS"),
66 # Patient information
67 (0x0010, 0x0010): ("PatientName", "PN"),
68 (0x0010, 0x0020): ("PatientID", "LO"),
69 (0x0010, 0x0030): ("PatientBirthDate", "DA"),
70 (0x0010, 0x0040): ("PatientSex", "CS"),
71 (0x0010, 0x1010): ("PatientAge", "AS"),
72 (0x0010, 0x1020): ("PatientSize", "DS"),
73 (0x0010, 0x1030): ("PatientWeight", "DS"),
74 # Image specific (required to construct numpy array)
75 (0x0028, 0x0002): ("SamplesPerPixel", "US"),
76 (0x0028, 0x0008): ("NumberOfFrames", "IS"),
77 (0x0028, 0x0100): ("BitsAllocated", "US"),
78 (0x0028, 0x0101): ("BitsStored", "US"),
79 (0x0028, 0x0102): ("HighBit", "US"),
80 (0x0028, 0x0103): ("PixelRepresentation", "US"),
81 (0x0028, 0x0010): ("Rows", "US"),
82 (0x0028, 0x0011): ("Columns", "US"),
83 (0x0028, 0x1052): ("RescaleIntercept", "DS"),
84 (0x0028, 0x1053): ("RescaleSlope", "DS"),
85 # Image specific (for the user)
86 (0x0028, 0x0030): ("PixelSpacing", "DS"),
87 (0x0018, 0x0088): ("SliceSpacing", "DS"),
88 }
89
90 # Define some special tags:
91 # See PS 3.5-2008 section 7.5 (p.40)
92 ItemTag = (0xFFFE, 0xE000) # start of Sequence Item
93 ItemDelimiterTag = (0xFFFE, 0xE00D) # end of Sequence Item
94 SequenceDelimiterTag = (0xFFFE, 0xE0DD) # end of Sequence of undefined length
95
96 # Define set of groups that we're interested in (so we can quickly skip others)
97 GROUPS = set([key[0] for key in MINIDICT.keys()])
98 VRS = set([val[1] for val in MINIDICT.values()])
99
100
101 class NotADicomFile(Exception):
102 pass
103
104
105 class CompressedDicom(RuntimeError):
106 pass
107
108
109 class SimpleDicomReader(object):
110 """
111 This class provides reading of pixel data from DICOM files. It is
112 focussed on getting the pixel data, not the meta info.
113
114 To use, first create an instance of this class (giving it
115 a file object or filename). Next use the info attribute to
116 get a dict of the meta data. The loading of pixel data is
117 deferred until get_numpy_array() is called.
118
119 Comparison with Pydicom
120 -----------------------
121
122 This code focusses on getting the pixel data out, which allows some
123 shortcuts, resulting in the code being much smaller.
124
125 Since the processing of data elements is much cheaper (it skips a lot
126 of tags), this code is about 3x faster than pydicom (except for the
127 deflated DICOM files).
128
129 This class does borrow some code (and ideas) from the pydicom
130 project, and (to the best of our knowledge) has the same limitations
131 as pydicom with regard to the type of files that it can handle.
132
133 Limitations
134 -----------
135
136 For more advanced DICOM processing, please check out pydicom.
137
138 * Only a predefined subset of data elements (meta information) is read.
139 * This is a reader; it can not write DICOM files.
140 * (just like pydicom) it can handle none of the compressed DICOM
141 formats except for "Deflated Explicit VR Little Endian"
142 (1.2.840.10008.1.2.1.99).
143
144 """
145
146 def __init__(self, file):
147 # Open file if filename given
148 if isinstance(file, str):
149 self._filename = file
150 self._file = open(file, "rb")
151 else:
152 self._filename = "<unknown file>"
153 self._file = file
154 # Init variable to store position and size of pixel data
155 self._pixel_data_loc = None
156 # The meta header is always explicit and little endian
157 self.is_implicit_VR = False
158 self.is_little_endian = True
159 self._unpackPrefix = "<"
160 # Dict to store data elements of interest in
161 self._info = {}
162 # VR Conversion
163 self._converters = {
164 # Numbers
165 "US": lambda x: self._unpack("H", x),
166 "UL": lambda x: self._unpack("L", x),
167 # Numbers encoded as strings
168 "DS": lambda x: self._splitValues(x, float, "\\"),
169 "IS": lambda x: self._splitValues(x, int, "\\"),
170 # strings
171 "AS": lambda x: x.decode("ascii", "ignore").strip("\x00"),
172 "DA": lambda x: x.decode("ascii", "ignore").strip("\x00"),
173 "TM": lambda x: x.decode("ascii", "ignore").strip("\x00"),
174 "UI": lambda x: x.decode("ascii", "ignore").strip("\x00"),
175 "LO": lambda x: x.decode("utf-8", "ignore").strip("\x00").rstrip(),
176 "CS": lambda x: self._splitValues(x, float, "\\"),
177 "PN": lambda x: x.decode("utf-8", "ignore").strip("\x00").rstrip(),
178 }
179
180 # Initiate reading
181 self._read()
182
183 @property
184 def info(self):
185 return self._info
186
187 def _splitValues(self, x, type, splitter):
188 s = x.decode("ascii").strip("\x00")
189 try:
190 if splitter in s:
191 return tuple([type(v) for v in s.split(splitter) if v.strip()])
192 else:
193 return type(s)
194 except ValueError:
195 return s
196
197 def _unpack(self, fmt, value):
198 return struct.unpack(self._unpackPrefix + fmt, value)[0]
199
200 # Really only so we need minimal changes to _pixel_data_numpy
201 def __iter__(self):
202 return iter(self._info.keys())
203
204 def __getattr__(self, key):
205 info = object.__getattribute__(self, "_info")
206 if key in info:
207 return info[key]
208 return object.__getattribute__(self, key) # pragma: no cover
209
210 def _read(self):
211 f = self._file
212 # Check prefix after peamble
213 f.seek(128)
214 if f.read(4) != b"DICM":
215 raise NotADicomFile("Not a valid DICOM file.")
216 # Read
217 self._read_header()
218 self._read_data_elements()
219 self._get_shape_and_sampling()
220 # Close if done, reopen if necessary to read pixel data
221 if os.path.isfile(self._filename):
222 self._file.close()
223 self._file = None
224
225 def _readDataElement(self):
226 f = self._file
227 # Get group and element
228 group = self._unpack("H", f.read(2))
229 element = self._unpack("H", f.read(2))
230 # Get value length
231 if self.is_implicit_VR:
232 vl = self._unpack("I", f.read(4))
233 else:
234 vr = f.read(2)
235 if vr in (b"OB", b"OW", b"SQ", b"UN"):
236 reserved = f.read(2) # noqa
237 vl = self._unpack("I", f.read(4))
238 else:
239 vl = self._unpack("H", f.read(2))
240 # Get value
241 if group == 0x7FE0 and element == 0x0010:
242 here = f.tell()
243 self._pixel_data_loc = here, vl
244 f.seek(here + vl)
245 return group, element, b"Deferred loading of pixel data"
246 else:
247 if vl == 0xFFFFFFFF:
248 value = self._read_undefined_length_value()
249 else:
250 value = f.read(vl)
251 return group, element, value
252
253 def _read_undefined_length_value(self, read_size=128):
254 """Copied (in compacted form) from PyDicom
255 Copyright Darcy Mason.
256 """
257 fp = self._file
258 # data_start = fp.tell()
259 search_rewind = 3
260 bytes_to_find = struct.pack(
261 self._unpackPrefix + "HH", SequenceDelimiterTag[0], SequenceDelimiterTag[1]
262 )
263
264 found = False
265 value_chunks = []
266 while not found:
267 chunk_start = fp.tell()
268 bytes_read = fp.read(read_size)
269 if len(bytes_read) < read_size:
270 # try again,
271 # if still don't get required amount, this is last block
272 new_bytes = fp.read(read_size - len(bytes_read))
273 bytes_read += new_bytes
274 if len(bytes_read) < read_size:
275 raise EOFError(
276 "End of file reached before sequence " "delimiter found."
277 )
278 index = bytes_read.find(bytes_to_find)
279 if index != -1:
280 found = True
281 value_chunks.append(bytes_read[:index])
282 fp.seek(chunk_start + index + 4) # rewind to end of delimiter
283 length = fp.read(4)
284 if length != b"\0\0\0\0":
285 logger.warning(
286 "Expected 4 zero bytes after undefined length " "delimiter"
287 )
288 else:
289 fp.seek(fp.tell() - search_rewind) # rewind a bit
290 # accumulate the bytes read (not including the rewind)
291 value_chunks.append(bytes_read[:-search_rewind])
292
293 # if get here then have found the byte string
294 return b"".join(value_chunks)
295
296 def _read_header(self):
297 f = self._file
298 TransferSyntaxUID = None
299
300 # Read all elements, store transferSyntax when we encounter it
301 try:
302 while True:
303 fp_save = f.tell()
304 # Get element
305 group, element, value = self._readDataElement()
306 if group == 0x02:
307 if group == 0x02 and element == 0x10:
308 TransferSyntaxUID = value.decode("ascii").strip("\x00")
309 else:
310 # No more group 2: rewind and break
311 # (don't trust group length)
312 f.seek(fp_save)
313 break
314 except (EOFError, struct.error): # pragma: no cover
315 raise RuntimeError("End of file reached while still in header.")
316
317 # Handle transfer syntax
318 self._info["TransferSyntaxUID"] = TransferSyntaxUID
319 #
320 if TransferSyntaxUID is None:
321 # Assume ExplicitVRLittleEndian
322 is_implicit_VR, is_little_endian = False, True
323 elif TransferSyntaxUID == "1.2.840.10008.1.2.1":
324 # ExplicitVRLittleEndian
325 is_implicit_VR, is_little_endian = False, True
326 elif TransferSyntaxUID == "1.2.840.10008.1.2.2":
327 # ExplicitVRBigEndian
328 is_implicit_VR, is_little_endian = False, False
329 elif TransferSyntaxUID == "1.2.840.10008.1.2":
330 # implicit VR little endian
331 is_implicit_VR, is_little_endian = True, True
332 elif TransferSyntaxUID == "1.2.840.10008.1.2.1.99":
333 # DeflatedExplicitVRLittleEndian:
334 is_implicit_VR, is_little_endian = False, True
335 self._inflate()
336 else:
337 # http://www.dicomlibrary.com/dicom/transfer-syntax/
338 t, extra_info = TransferSyntaxUID, ""
339 if "1.2.840.10008.1.2.4.50" <= t < "1.2.840.10008.1.2.4.99":
340 extra_info = " (JPEG)"
341 if "1.2.840.10008.1.2.4.90" <= t < "1.2.840.10008.1.2.4.99":
342 extra_info = " (JPEG 2000)"
343 if t == "1.2.840.10008.1.2.5":
344 extra_info = " (RLE)"
345 if t == "1.2.840.10008.1.2.6.1":
346 extra_info = " (RFC 2557)"
347 raise CompressedDicom(
348 "The dicom reader can only read files with "
349 "uncompressed image data - not %r%s. You "
350 "can try using dcmtk or gdcm to convert the "
351 "image." % (t, extra_info)
352 )
353
354 # From hereon, use implicit/explicit big/little endian
355 self.is_implicit_VR = is_implicit_VR
356 self.is_little_endian = is_little_endian
357 self._unpackPrefix = "><"[is_little_endian]
358
359 def _read_data_elements(self):
360 info = self._info
361 try:
362 while True:
363 # Get element
364 group, element, value = self._readDataElement()
365 # Is it a group we are interested in?
366 if group in GROUPS:
367 key = (group, element)
368 name, vr = MINIDICT.get(key, (None, None))
369 # Is it an element we are interested in?
370 if name:
371 # Store value
372 converter = self._converters.get(vr, lambda x: x)
373 info[name] = converter(value)
374 except (EOFError, struct.error):
375 pass # end of file ...
376
377 def get_numpy_array(self):
378 """Get numpy arra for this DICOM file, with the correct shape,
379 and pixel values scaled appropriately.
380 """
381 # Is there pixel data at all?
382 if "PixelData" not in self:
383 raise TypeError("No pixel data found in this dataset.")
384
385 # Load it now if it was not already loaded
386 if self._pixel_data_loc and len(self.PixelData) < 100:
387 # Reopen file?
388 close_file = False
389 if self._file is None:
390 close_file = True
391 self._file = open(self._filename, "rb")
392 # Read data
393 self._file.seek(self._pixel_data_loc[0])
394 if self._pixel_data_loc[1] == 0xFFFFFFFF:
395 value = self._read_undefined_length_value()
396 else:
397 value = self._file.read(self._pixel_data_loc[1])
398 # Close file
399 if close_file:
400 self._file.close()
401 self._file = None
402 # Overwrite
403 self._info["PixelData"] = value
404
405 # Get data
406 data = self._pixel_data_numpy()
407 data = self._apply_slope_and_offset(data)
408
409 # Remove data again to preserve memory
410 # Note that the data for the original file is loaded twice ...
411 self._info["PixelData"] = (
412 b"Data converted to numpy array, " + b"raw data removed to preserve memory"
413 )
414 return data
415
416 def _get_shape_and_sampling(self):
417 """Get shape and sampling without actuall using the pixel data.
418 In this way, the user can get an idea what's inside without having
419 to load it.
420 """
421 # Get shape (in the same way that pydicom does)
422 if "NumberOfFrames" in self and self.NumberOfFrames > 1:
423 if self.SamplesPerPixel > 1:
424 shape = (
425 self.SamplesPerPixel,
426 self.NumberOfFrames,
427 self.Rows,
428 self.Columns,
429 )
430 else:
431 shape = self.NumberOfFrames, self.Rows, self.Columns
432 elif "SamplesPerPixel" in self:
433 if self.SamplesPerPixel > 1:
434 if self.BitsAllocated == 8:
435 shape = self.SamplesPerPixel, self.Rows, self.Columns
436 else:
437 raise NotImplementedError(
438 "DICOM plugin only handles "
439 "SamplesPerPixel > 1 if Bits "
440 "Allocated = 8"
441 )
442 else:
443 shape = self.Rows, self.Columns
444 else:
445 raise RuntimeError(
446 "DICOM file has no SamplesPerPixel " "(perhaps this is a report?)"
447 )
448
449 # Try getting sampling between pixels
450 if "PixelSpacing" in self:
451 sampling = float(self.PixelSpacing[0]), float(self.PixelSpacing[1])
452 else:
453 sampling = 1.0, 1.0
454 if "SliceSpacing" in self:
455 sampling = (abs(self.SliceSpacing),) + sampling
456
457 # Ensure that sampling has as many elements as shape
458 sampling = (1.0,) * (len(shape) - len(sampling)) + sampling[-len(shape) :]
459
460 # Set shape and sampling
461 self._info["shape"] = shape
462 self._info["sampling"] = sampling
463
464 def _pixel_data_numpy(self):
465 """Return a NumPy array of the pixel data."""
466 # Taken from pydicom
467 # Copyright (c) 2008-2012 Darcy Mason
468
469 if "PixelData" not in self:
470 raise TypeError("No pixel data found in this dataset.")
471
472 # determine the type used for the array
473 need_byteswap = self.is_little_endian != sys_is_little_endian
474
475 # Make NumPy format code, e.g. "uint16", "int32" etc
476 # from two pieces of info:
477 # self.PixelRepresentation -- 0 for unsigned, 1 for signed;
478 # self.BitsAllocated -- 8, 16, or 32
479 format_str = "%sint%d" % (
480 ("u", "")[self.PixelRepresentation],
481 self.BitsAllocated,
482 )
483 try:
484 numpy_format = np.dtype(format_str)
485 except TypeError: # pragma: no cover
486 raise TypeError(
487 "Data type not understood by NumPy: format='%s', "
488 " PixelRepresentation=%d, BitsAllocated=%d"
489 % (numpy_format, self.PixelRepresentation, self.BitsAllocated)
490 )
491
492 # Have correct Numpy format, so create the NumPy array
493 arr = np.frombuffer(self.PixelData, numpy_format).copy()
494
495 # XXX byte swap - may later handle this in read_file!!?
496 if need_byteswap:
497 arr.byteswap(True) # True means swap in-place, don't make new copy
498
499 # Note the following reshape operations return a new *view* onto arr,
500 # but don't copy the data
501 arr = arr.reshape(*self._info["shape"])
502 return arr
503
504 def _apply_slope_and_offset(self, data):
505 """
506 If RescaleSlope and RescaleIntercept are present in the data,
507 apply them. The data type of the data is changed if necessary.
508 """
509 # Obtain slope and offset
510 slope, offset = 1, 0
511 needFloats, needApplySlopeOffset = False, False
512 if "RescaleSlope" in self:
513 needApplySlopeOffset = True
514 slope = self.RescaleSlope
515 if "RescaleIntercept" in self:
516 needApplySlopeOffset = True
517 offset = self.RescaleIntercept
518 if int(slope) != slope or int(offset) != offset:
519 needFloats = True
520 if not needFloats:
521 slope, offset = int(slope), int(offset)
522
523 # Apply slope and offset
524 if needApplySlopeOffset:
525 # Maybe we need to change the datatype?
526 if data.dtype in [np.float32, np.float64]:
527 pass
528 elif needFloats:
529 data = data.astype(np.float32)
530 else:
531 # Determine required range
532 minReq, maxReq = data.min().item(), data.max().item()
533 minReq = min([minReq, minReq * slope + offset, maxReq * slope + offset])
534 maxReq = max([maxReq, minReq * slope + offset, maxReq * slope + offset])
535
536 # Determine required datatype from that
537 dtype = None
538 if minReq < 0:
539 # Signed integer type
540 maxReq = max([-minReq, maxReq])
541 if maxReq < 2**7:
542 dtype = np.int8
543 elif maxReq < 2**15:
544 dtype = np.int16
545 elif maxReq < 2**31:
546 dtype = np.int32
547 else:
548 dtype = np.float32
549 else:
550 # Unsigned integer type
551 if maxReq < 2**8:
552 dtype = np.int8
553 elif maxReq < 2**16:
554 dtype = np.int16
555 elif maxReq < 2**32:
556 dtype = np.int32
557 else:
558 dtype = np.float32
559 # Change datatype
560 if dtype != data.dtype:
561 data = data.astype(dtype)
562
563 # Apply slope and offset
564 data *= slope
565 data += offset
566
567 # Done
568 return data
569
570 def _inflate(self):
571 # Taken from pydicom
572 # Copyright (c) 2008-2012 Darcy Mason
573 import zlib
574 from io import BytesIO
575
576 # See PS3.6-2008 A.5 (p 71) -- when written, the entire dataset
577 # following the file metadata was prepared the normal way,
578 # then "deflate" compression applied.
579 # All that is needed here is to decompress and then
580 # use as normal in a file-like object
581 zipped = self._file.read()
582 # -MAX_WBITS part is from comp.lang.python answer:
583 # groups.google.com/group/comp.lang.python/msg/e95b3b38a71e6799
584 unzipped = zlib.decompress(zipped, -zlib.MAX_WBITS)
585 self._file = BytesIO(unzipped) # a file-like object
586
587
588 class DicomSeries(object):
589 """DicomSeries
590 This class represents a serie of dicom files (SimpleDicomReader
591 objects) that belong together. If these are multiple files, they
592 represent the slices of a volume (like for CT or MRI).
593 """
594
595 def __init__(self, suid, progressIndicator):
596 # Init dataset list and the callback
597 self._entries = []
598
599 # Init props
600 self._suid = suid
601 self._info = {}
602 self._progressIndicator = progressIndicator
603
604 def __len__(self):
605 return len(self._entries)
606
607 def __iter__(self):
608 return iter(self._entries)
609
610 def __getitem__(self, index):
611 return self._entries[index]
612
613 @property
614 def suid(self):
615 return self._suid
616
617 @property
618 def shape(self):
619 """The shape of the data (nz, ny, nx)."""
620 return self._info["shape"]
621
622 @property
623 def sampling(self):
624 """The sampling (voxel distances) of the data (dz, dy, dx)."""
625 return self._info["sampling"]
626
627 @property
628 def info(self):
629 """A dictionary containing the information as present in the
630 first dicomfile of this serie. None if there are no entries."""
631 return self._info
632
633 @property
634 def description(self):
635 """A description of the dicom series. Used fields are
636 PatientName, shape of the data, SeriesDescription, and
637 ImageComments.
638 """
639 info = self.info
640
641 # If no info available, return simple description
642 if not info: # pragma: no cover
643 return "DicomSeries containing %i images" % len(self)
644
645 fields = []
646 # Give patient name
647 if "PatientName" in info:
648 fields.append("" + info["PatientName"])
649 # Also add dimensions
650 if self.shape:
651 tmp = [str(d) for d in self.shape]
652 fields.append("x".join(tmp))
653 # Try adding more fields
654 if "SeriesDescription" in info:
655 fields.append("'" + info["SeriesDescription"] + "'")
656 if "ImageComments" in info:
657 fields.append("'" + info["ImageComments"] + "'")
658
659 # Combine
660 return " ".join(fields)
661
662 def __repr__(self):
663 adr = hex(id(self)).upper()
664 return "<DicomSeries with %i images at %s>" % (len(self), adr)
665
666 def get_numpy_array(self):
667 """Get (load) the data that this DicomSeries represents, and return
668 it as a numpy array. If this serie contains multiple images, the
669 resulting array is 3D, otherwise it's 2D.
670 """
671
672 # It's easy if no file or if just a single file
673 if len(self) == 0:
674 raise ValueError("Serie does not contain any files.")
675 elif len(self) == 1:
676 return self[0].get_numpy_array()
677
678 # Check info
679 if self.info is None:
680 raise RuntimeError("Cannot return volume if series not finished.")
681
682 # Init data (using what the dicom packaged produces as a reference)
683 slice = self[0].get_numpy_array()
684 vol = np.zeros(self.shape, dtype=slice.dtype)
685 vol[0] = slice
686
687 # Fill volume
688 self._progressIndicator.start("loading data", "", len(self))
689 for z in range(1, len(self)):
690 vol[z] = self[z].get_numpy_array()
691 self._progressIndicator.set_progress(z + 1)
692 self._progressIndicator.finish()
693
694 # Done
695 import gc
696
697 gc.collect()
698 return vol
699
700 def _append(self, dcm):
701 self._entries.append(dcm)
702
703 def _sort(self):
704 self._entries.sort(
705 key=lambda k: (
706 k.InstanceNumber,
707 (
708 k.ImagePositionPatient[2]
709 if hasattr(k, "ImagePositionPatient")
710 else None
711 ),
712 )
713 )
714
715 def _finish(self):
716 """
717 Evaluate the series of dicom files. Together they should make up
718 a volumetric dataset. This means the files should meet certain
719 conditions. Also some additional information has to be calculated,
720 such as the distance between the slices. This method sets the
721 attributes for "shape", "sampling" and "info".
722
723 This method checks:
724 * that there are no missing files
725 * that the dimensions of all images match
726 * that the pixel spacing of all images match
727 """
728
729 # The datasets list should be sorted by instance number
730 L = self._entries
731 if len(L) == 0:
732 return
733 elif len(L) == 1:
734 self._info = L[0].info
735 return
736
737 # Get previous
738 ds1 = L[0]
739 # Init measures to calculate average of
740 distance_sum = 0.0
741 # Init measures to check (these are in 2D)
742 dimensions = ds1.Rows, ds1.Columns
743 # sampling = float(ds1.PixelSpacing[0]), float(ds1.PixelSpacing[1])
744 sampling = ds1.info["sampling"][:2] # row, column
745
746 for index in range(len(L)):
747 # The first round ds1 and ds2 will be the same, for the
748 # distance calculation this does not matter
749 # Get current
750 ds2 = L[index]
751 # Get positions
752 pos1 = float(ds1.ImagePositionPatient[2])
753 pos2 = float(ds2.ImagePositionPatient[2])
754 # Update distance_sum to calculate distance later
755 distance_sum += abs(pos1 - pos2)
756 # Test measures
757 dimensions2 = ds2.Rows, ds2.Columns
758 # sampling2 = float(ds2.PixelSpacing[0]), float(ds2.PixelSpacing[1])
759 sampling2 = ds2.info["sampling"][:2] # row, column
760 if dimensions != dimensions2:
761 # We cannot produce a volume if the dimensions match
762 raise ValueError("Dimensions of slices does not match.")
763 if sampling != sampling2:
764 # We can still produce a volume, but we should notify the user
765 self._progressIndicator.write("Warn: sampling does not match.")
766 # Store previous
767 ds1 = ds2
768
769 # Finish calculating average distance
770 # (Note that there are len(L)-1 distances)
771 distance_mean = distance_sum / (len(L) - 1)
772
773 # Set info dict
774 self._info = L[0].info.copy()
775
776 # Store information that is specific for the serie
777 self._info["shape"] = (len(L),) + ds2.info["shape"]
778 self._info["sampling"] = (distance_mean,) + ds2.info["sampling"]
779
780
781 def list_files(files, path):
782 """List all files in the directory, recursively."""
783 for item in os.listdir(path):
784 item = os.path.join(path, item)
785 if os.path.isdir(item):
786 list_files(files, item)
787 elif os.path.isfile(item):
788 files.append(item)
789
790
791 def process_directory(request, progressIndicator, readPixelData=False):
792 """
793 Reads dicom files and returns a list of DicomSeries objects, which
794 contain information about the data, and can be used to load the
795 image or volume data.
796
797 if readPixelData is True, the pixel data of all series is read. By
798 default the loading of pixeldata is deferred until it is requested
799 using the DicomSeries.get_pixel_array() method. In general, both
800 methods should be equally fast.
801 """
802 # Get directory to examine
803 if os.path.isdir(request.filename):
804 path = request.filename
805 elif os.path.isfile(request.filename):
806 path = os.path.dirname(request.filename)
807 else: # pragma: no cover - tested earlier
808 raise ValueError("Dicom plugin needs a valid filename to examine the directory")
809
810 # Check files
811 files = []
812 list_files(files, path) # Find files recursively
813
814 # Gather file data and put in DicomSeries
815 series = {}
816 count = 0
817 progressIndicator.start("examining files", "files", len(files))
818 for filename in files:
819 # Show progress (note that we always start with a 0.0)
820 count += 1
821 progressIndicator.set_progress(count)
822 # Skip DICOMDIR files
823 if filename.count("DICOMDIR"): # pragma: no cover
824 continue
825 # Try loading dicom ...
826 try:
827 dcm = SimpleDicomReader(filename)
828 except NotADicomFile:
829 continue # skip non-dicom file
830 except Exception as why: # pragma: no cover
831 progressIndicator.write(str(why))
832 continue
833 # Get SUID and register the file with an existing or new series object
834 try:
835 suid = dcm.SeriesInstanceUID
836 except AttributeError: # pragma: no cover
837 continue # some other kind of dicom file
838 if suid not in series:
839 series[suid] = DicomSeries(suid, progressIndicator)
840 series[suid]._append(dcm)
841
842 # Finish progress
843 # progressIndicator.finish('Found %i series.' % len(series))
844
845 # Make a list and sort, so that the order is deterministic
846 series = list(series.values())
847 series.sort(key=lambda x: x.suid)
848
849 # Split series if necessary
850 for serie in reversed([serie for serie in series]):
851 splitSerieIfRequired(serie, series, progressIndicator)
852
853 # Finish all series
854 # progressIndicator.start('analyse series', '', len(series))
855 series_ = []
856 for i in range(len(series)):
857 try:
858 series[i]._finish()
859 series_.append(series[i])
860 except Exception as err: # pragma: no cover
861 progressIndicator.write(str(err))
862 pass # Skip serie (probably report-like file without pixels)
863 # progressIndicator.set_progress(i+1)
864 progressIndicator.finish("Found %i correct series." % len(series_))
865
866 # Done
867 return series_
868
869
870 def splitSerieIfRequired(serie, series, progressIndicator):
871 """
872 Split the serie in multiple series if this is required. The choice
873 is based on examing the image position relative to the previous
874 image. If it differs too much, it is assumed that there is a new
875 dataset. This can happen for example in unspitted gated CT data.
876 """
877
878 # Sort the original list and get local name
879 serie._sort()
880 L = serie._entries
881 # Init previous slice
882 ds1 = L[0]
883 # Check whether we can do this
884 if "ImagePositionPatient" not in ds1:
885 return
886 # Initialize a list of new lists
887 L2 = [[ds1]]
888 # Init slice distance estimate
889 distance = 0
890
891 for index in range(1, len(L)):
892 # Get current slice
893 ds2 = L[index]
894 # Get positions
895 pos1 = float(ds1.ImagePositionPatient[2])
896 pos2 = float(ds2.ImagePositionPatient[2])
897 # Get distances
898 newDist = abs(pos1 - pos2)
899 # deltaDist = abs(firstPos-pos2)
900 # If the distance deviates more than 2x from what we've seen,
901 # we can agree it's a new dataset.
902 if distance and newDist > 2.1 * distance:
903 L2.append([])
904 distance = 0
905 else:
906 # Test missing file
907 if distance and newDist > 1.5 * distance:
908 progressIndicator.write(
909 "Warning: missing file after %r" % ds1._filename
910 )
911 distance = newDist
912 # Add to last list
913 L2[-1].append(ds2)
914 # Store previous
915 ds1 = ds2
916
917 # Split if we should
918 if len(L2) > 1:
919 # At what position are we now?
920 i = series.index(serie)
921 # Create new series
922 series2insert = []
923 for L in L2:
924 newSerie = DicomSeries(serie.suid, progressIndicator)
925 newSerie._entries = L
926 series2insert.append(newSerie)
927 # Insert series and remove self
928 for newSerie in reversed(series2insert):
929 series.insert(i, newSerie)
930 series.remove(serie)