| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
"""Plugin for reading DICOM files.""" |
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 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 |
|
| 24 |
sys_is_little_endian = sys.byteorder == "little" |
| 25 |
|
| 26 |
|
| 27 |
MINIDICT = { |
| 28 |
(0x7FE0, 0x0010): ("PixelData", "OB"), |
| 29 |
|
| 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 |
|
| 39 |
(0x0008, 0x0060): ("Modality", "CS"), |
| 40 |
(0x0008, 0x0070): ("Manufacturer", "LO"), |
| 41 |
(0x0008, 0x0080): ("InstitutionName", "LO"), |
| 42 |
|
| 43 |
(0x0008, 0x1030): ("StudyDescription", "LO"), |
| 44 |
(0x0008, 0x103E): ("SeriesDescription", "LO"), |
| 45 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 86 |
(0x0028, 0x0030): ("PixelSpacing", "DS"), |
| 87 |
(0x0018, 0x0088): ("SliceSpacing", "DS"), |
| 88 |
} |
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
ItemTag = (0xFFFE, 0xE000) |
| 93 |
ItemDelimiterTag = (0xFFFE, 0xE00D) |
| 94 |
SequenceDelimiterTag = (0xFFFE, 0xE0DD) |
| 95 |
|
| 96 |
|
| 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 |
|
| 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 |
|
| 155 |
self._pixel_data_loc = None |
| 156 |
|
| 157 |
self.is_implicit_VR = False |
| 158 |
self.is_little_endian = True |
| 159 |
self._unpackPrefix = "<" |
| 160 |
|
| 161 |
self._info = {} |
| 162 |
|
| 163 |
self._converters = { |
| 164 |
|
| 165 |
"US": lambda x: self._unpack("H", x), |
| 166 |
"UL": lambda x: self._unpack("L", x), |
| 167 |
|
| 168 |
"DS": lambda x: self._splitValues(x, float, "\\"), |
| 169 |
"IS": lambda x: self._splitValues(x, int, "\\"), |
| 170 |
|
| 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 |
|
| 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 |
|
| 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) |
| 209 |
|
| 210 |
def _read(self): |
| 211 |
f = self._file |
| 212 |
|
| 213 |
f.seek(128) |
| 214 |
if f.read(4) != b"DICM": |
| 215 |
raise NotADicomFile("Not a valid DICOM file.") |
| 216 |
|
| 217 |
self._read_header() |
| 218 |
self._read_data_elements() |
| 219 |
self._get_shape_and_sampling() |
| 220 |
|
| 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 |
|
| 228 |
group = self._unpack("H", f.read(2)) |
| 229 |
element = self._unpack("H", f.read(2)) |
| 230 |
|
| 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) |
| 237 |
vl = self._unpack("I", f.read(4)) |
| 238 |
else: |
| 239 |
vl = self._unpack("H", f.read(2)) |
| 240 |
|
| 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 |
|
| 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 |
|
| 271 |
|
| 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) |
| 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) |
| 290 |
|
| 291 |
value_chunks.append(bytes_read[:-search_rewind]) |
| 292 |
|
| 293 |
|
| 294 |
return b"".join(value_chunks) |
| 295 |
|
| 296 |
def _read_header(self): |
| 297 |
f = self._file |
| 298 |
TransferSyntaxUID = None |
| 299 |
|
| 300 |
|
| 301 |
try: |
| 302 |
while True: |
| 303 |
fp_save = f.tell() |
| 304 |
|
| 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 |
|
| 311 |
|
| 312 |
f.seek(fp_save) |
| 313 |
break |
| 314 |
except (EOFError, struct.error): |
| 315 |
raise RuntimeError("End of file reached while still in header.") |
| 316 |
|
| 317 |
|
| 318 |
self._info["TransferSyntaxUID"] = TransferSyntaxUID |
| 319 |
|
| 320 |
if TransferSyntaxUID is None: |
| 321 |
|
| 322 |
is_implicit_VR, is_little_endian = False, True |
| 323 |
elif TransferSyntaxUID == "1.2.840.10008.1.2.1": |
| 324 |
|
| 325 |
is_implicit_VR, is_little_endian = False, True |
| 326 |
elif TransferSyntaxUID == "1.2.840.10008.1.2.2": |
| 327 |
|
| 328 |
is_implicit_VR, is_little_endian = False, False |
| 329 |
elif TransferSyntaxUID == "1.2.840.10008.1.2": |
| 330 |
|
| 331 |
is_implicit_VR, is_little_endian = True, True |
| 332 |
elif TransferSyntaxUID == "1.2.840.10008.1.2.1.99": |
| 333 |
|
| 334 |
is_implicit_VR, is_little_endian = False, True |
| 335 |
self._inflate() |
| 336 |
else: |
| 337 |
|
| 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 |
|
| 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 |
|
| 364 |
group, element, value = self._readDataElement() |
| 365 |
|
| 366 |
if group in GROUPS: |
| 367 |
key = (group, element) |
| 368 |
name, vr = MINIDICT.get(key, (None, None)) |
| 369 |
|
| 370 |
if name: |
| 371 |
|
| 372 |
converter = self._converters.get(vr, lambda x: x) |
| 373 |
info[name] = converter(value) |
| 374 |
except (EOFError, struct.error): |
| 375 |
pass |
| 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 |
|
| 382 |
if "PixelData" not in self: |
| 383 |
raise TypeError("No pixel data found in this dataset.") |
| 384 |
|
| 385 |
|
| 386 |
if self._pixel_data_loc and len(self.PixelData) < 100: |
| 387 |
|
| 388 |
close_file = False |
| 389 |
if self._file is None: |
| 390 |
close_file = True |
| 391 |
self._file = open(self._filename, "rb") |
| 392 |
|
| 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 |
|
| 399 |
if close_file: |
| 400 |
self._file.close() |
| 401 |
self._file = None |
| 402 |
|
| 403 |
self._info["PixelData"] = value |
| 404 |
|
| 405 |
|
| 406 |
data = self._pixel_data_numpy() |
| 407 |
data = self._apply_slope_and_offset(data) |
| 408 |
|
| 409 |
|
| 410 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 458 |
sampling = (1.0,) * (len(shape) - len(sampling)) + sampling[-len(shape) :] |
| 459 |
|
| 460 |
|
| 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 |
|
| 467 |
|
| 468 |
|
| 469 |
if "PixelData" not in self: |
| 470 |
raise TypeError("No pixel data found in this dataset.") |
| 471 |
|
| 472 |
|
| 473 |
need_byteswap = self.is_little_endian != sys_is_little_endian |
| 474 |
|
| 475 |
|
| 476 |
|
| 477 |
|
| 478 |
|
| 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: |
| 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 |
|
| 493 |
arr = np.frombuffer(self.PixelData, numpy_format).copy() |
| 494 |
|
| 495 |
|
| 496 |
if need_byteswap: |
| 497 |
arr.byteswap(True) |
| 498 |
|
| 499 |
|
| 500 |
|
| 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 |
|
| 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 |
|
| 524 |
if needApplySlopeOffset: |
| 525 |
|
| 526 |
if data.dtype in [np.float32, np.float64]: |
| 527 |
pass |
| 528 |
elif needFloats: |
| 529 |
data = data.astype(np.float32) |
| 530 |
else: |
| 531 |
|
| 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 |
|
| 537 |
dtype = None |
| 538 |
if minReq < 0: |
| 539 |
|
| 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 |
|
| 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 |
|
| 560 |
if dtype != data.dtype: |
| 561 |
data = data.astype(dtype) |
| 562 |
|
| 563 |
|
| 564 |
data *= slope |
| 565 |
data += offset |
| 566 |
|
| 567 |
|
| 568 |
return data |
| 569 |
|
| 570 |
def _inflate(self): |
| 571 |
|
| 572 |
|
| 573 |
import zlib |
| 574 |
from io import BytesIO |
| 575 |
|
| 576 |
|
| 577 |
|
| 578 |
|
| 579 |
|
| 580 |
|
| 581 |
zipped = self._file.read() |
| 582 |
|
| 583 |
|
| 584 |
unzipped = zlib.decompress(zipped, -zlib.MAX_WBITS) |
| 585 |
self._file = BytesIO(unzipped) |
| 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 |
|
| 597 |
self._entries = [] |
| 598 |
|
| 599 |
|
| 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 |
|
| 642 |
if not info: |
| 643 |
return "DicomSeries containing %i images" % len(self) |
| 644 |
|
| 645 |
fields = [] |
| 646 |
|
| 647 |
if "PatientName" in info: |
| 648 |
fields.append("" + info["PatientName"]) |
| 649 |
|
| 650 |
if self.shape: |
| 651 |
tmp = [str(d) for d in self.shape] |
| 652 |
fields.append("x".join(tmp)) |
| 653 |
|
| 654 |
if "SeriesDescription" in info: |
| 655 |
fields.append("'" + info["SeriesDescription"] + "'") |
| 656 |
if "ImageComments" in info: |
| 657 |
fields.append("'" + info["ImageComments"] + "'") |
| 658 |
|
| 659 |
|
| 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 |
|
| 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 |
|
| 679 |
if self.info is None: |
| 680 |
raise RuntimeError("Cannot return volume if series not finished.") |
| 681 |
|
| 682 |
|
| 683 |
slice = self[0].get_numpy_array() |
| 684 |
vol = np.zeros(self.shape, dtype=slice.dtype) |
| 685 |
vol[0] = slice |
| 686 |
|
| 687 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 738 |
ds1 = L[0] |
| 739 |
|
| 740 |
distance_sum = 0.0 |
| 741 |
|
| 742 |
dimensions = ds1.Rows, ds1.Columns |
| 743 |
|
| 744 |
sampling = ds1.info["sampling"][:2] |
| 745 |
|
| 746 |
for index in range(len(L)): |
| 747 |
|
| 748 |
|
| 749 |
|
| 750 |
ds2 = L[index] |
| 751 |
|
| 752 |
pos1 = float(ds1.ImagePositionPatient[2]) |
| 753 |
pos2 = float(ds2.ImagePositionPatient[2]) |
| 754 |
|
| 755 |
distance_sum += abs(pos1 - pos2) |
| 756 |
|
| 757 |
dimensions2 = ds2.Rows, ds2.Columns |
| 758 |
|
| 759 |
sampling2 = ds2.info["sampling"][:2] |
| 760 |
if dimensions != dimensions2: |
| 761 |
|
| 762 |
raise ValueError("Dimensions of slices does not match.") |
| 763 |
if sampling != sampling2: |
| 764 |
|
| 765 |
self._progressIndicator.write("Warn: sampling does not match.") |
| 766 |
|
| 767 |
ds1 = ds2 |
| 768 |
|
| 769 |
|
| 770 |
|
| 771 |
distance_mean = distance_sum / (len(L) - 1) |
| 772 |
|
| 773 |
|
| 774 |
self._info = L[0].info.copy() |
| 775 |
|
| 776 |
|
| 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 |
|
| 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: |
| 808 |
raise ValueError("Dicom plugin needs a valid filename to examine the directory") |
| 809 |
|
| 810 |
|
| 811 |
files = [] |
| 812 |
list_files(files, path) |
| 813 |
|
| 814 |
|
| 815 |
series = {} |
| 816 |
count = 0 |
| 817 |
progressIndicator.start("examining files", "files", len(files)) |
| 818 |
for filename in files: |
| 819 |
|
| 820 |
count += 1 |
| 821 |
progressIndicator.set_progress(count) |
| 822 |
|
| 823 |
if filename.count("DICOMDIR"): |
| 824 |
continue |
| 825 |
|
| 826 |
try: |
| 827 |
dcm = SimpleDicomReader(filename) |
| 828 |
except NotADicomFile: |
| 829 |
continue |
| 830 |
except Exception as why: |
| 831 |
progressIndicator.write(str(why)) |
| 832 |
continue |
| 833 |
|
| 834 |
try: |
| 835 |
suid = dcm.SeriesInstanceUID |
| 836 |
except AttributeError: |
| 837 |
continue |
| 838 |
if suid not in series: |
| 839 |
series[suid] = DicomSeries(suid, progressIndicator) |
| 840 |
series[suid]._append(dcm) |
| 841 |
|
| 842 |
|
| 843 |
|
| 844 |
|
| 845 |
|
| 846 |
series = list(series.values()) |
| 847 |
series.sort(key=lambda x: x.suid) |
| 848 |
|
| 849 |
|
| 850 |
for serie in reversed([serie for serie in series]): |
| 851 |
splitSerieIfRequired(serie, series, progressIndicator) |
| 852 |
|
| 853 |
|
| 854 |
|
| 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: |
| 861 |
progressIndicator.write(str(err)) |
| 862 |
pass |
| 863 |
|
| 864 |
progressIndicator.finish("Found %i correct series." % len(series_)) |
| 865 |
|
| 866 |
|
| 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 |
|
| 879 |
serie._sort() |
| 880 |
L = serie._entries |
| 881 |
|
| 882 |
ds1 = L[0] |
| 883 |
|
| 884 |
if "ImagePositionPatient" not in ds1: |
| 885 |
return |
| 886 |
|
| 887 |
L2 = [[ds1]] |
| 888 |
|
| 889 |
distance = 0 |
| 890 |
|
| 891 |
for index in range(1, len(L)): |
| 892 |
|
| 893 |
ds2 = L[index] |
| 894 |
|
| 895 |
pos1 = float(ds1.ImagePositionPatient[2]) |
| 896 |
pos2 = float(ds2.ImagePositionPatient[2]) |
| 897 |
|
| 898 |
newDist = abs(pos1 - pos2) |
| 899 |
|
| 900 |
|
| 901 |
|
| 902 |
if distance and newDist > 2.1 * distance: |
| 903 |
L2.append([]) |
| 904 |
distance = 0 |
| 905 |
else: |
| 906 |
|
| 907 |
if distance and newDist > 1.5 * distance: |
| 908 |
progressIndicator.write( |
| 909 |
"Warning: missing file after %r" % ds1._filename |
| 910 |
) |
| 911 |
distance = newDist |
| 912 |
|
| 913 |
L2[-1].append(ds2) |
| 914 |
|
| 915 |
ds1 = ds2 |
| 916 |
|
| 917 |
|
| 918 |
if len(L2) > 1: |
| 919 |
|
| 920 |
i = series.index(serie) |
| 921 |
|
| 922 |
series2insert = [] |
| 923 |
for L in L2: |
| 924 |
newSerie = DicomSeries(serie.suid, progressIndicator) |
| 925 |
newSerie._entries = L |
| 926 |
series2insert.append(newSerie) |
| 927 |
|
| 928 |
for newSerie in reversed(series2insert): |
| 929 |
series.insert(i, newSerie) |
| 930 |
series.remove(serie) |