|
21 | 21 | from concurrent.futures import ProcessPoolExecutor, as_completed |
22 | 22 | from io import BytesIO |
23 | 23 | from glob import glob |
| 24 | +from warnings import warn |
24 | 25 |
|
25 | 26 | import numpy as np |
26 | 27 | from pydicom import dicomio, datadict, errors |
|
65 | 66 | FULL_NAME_MAP = {v: k for k, v in KEYWORD_NAME_MAP.items()} # maps full names to keywords |
66 | 67 |
|
67 | 68 |
|
| 69 | +def get_2d_equivalent_image(img): |
| 70 | + """Given an array `img` of some arbitrary dimensions, attempt to choose a valid 2D gray/RGB/RGBA image from it.""" |
| 71 | + ndim = img.ndim |
| 72 | + shape = img.shape |
| 73 | + color_dim = ndim > 2 and shape[-1] in (1, 3, 4) |
| 74 | + |
| 75 | + if ndim <= 2 or (ndim == 3 and color_dim): # 0D array, 1D array, 2D grayscale or 2D RGB(A) |
| 76 | + if ndim < 2: |
| 77 | + warn(f"Image has unusual shape {shape}, attempting to visualise") |
| 78 | + |
| 79 | + return img |
| 80 | + elif ndim == 3: # 3D grayscale |
| 81 | + warn(f"Image is volume with shape {shape}, using mid-slice") |
| 82 | + elif ndim == 4 and color_dim: |
| 83 | + warn(f"Image is RGB(A) volume with shape {shape}, using mid-slice") |
| 84 | + else: |
| 85 | + warn(f"Image is unknown volume with shape {shape}, using mid-slices") |
| 86 | + |
| 87 | + # attempt to slice the volume in every dimension that's not height, width, or the channels |
| 88 | + stop = 3 if color_dim else 2 # dimensions to not slice in, ie. (height,width) or (height,width,channels) |
| 89 | + slices = [s // 2 for s in shape[:-stop]] + [slice(None)] * stop |
| 90 | + return img[tuple(slices)] |
| 91 | + |
| 92 | + |
68 | 93 | def get_scaled_image(dcm): |
69 | 94 | """Return image data from `dcm` scaled using slope and intercept values.""" |
70 | 95 | try: |
|
0 commit comments