File size: 4,048 Bytes
1024e04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
"""DICOM input checks; no source files or patient metadata are modified."""
from pathlib import Path

MIN_FRAMES = 10
MAX_FRAMES = 1024
MAX_DECODED_BYTES = 512 * 1024 * 1024


class InferenceError(RuntimeError):
    """An actionable validation or inference failure, never a numeric fallback."""


def inspect(path):
    import pydicom
    tags = ["StudyInstanceUID", "SeriesInstanceUID", "SOPInstanceUID", "NumberOfFrames",
            "Rows", "Columns", "SamplesPerPixel", "BitsAllocated", "PixelRepresentation",
            "PhotometricInterpretation"]
    try:
        ds = pydicom.dcmread(str(path), stop_before_pixels=True, specific_tags=tags)
        result = {
            "path": str(path),
            "study_uid": str(ds.get("StudyInstanceUID", "")),
            "series_uid": str(ds.get("SeriesInstanceUID", "")),
            "sop_uid": str(ds.get("SOPInstanceUID", "")),
            "frames": int(ds.get("NumberOfFrames", 1)),
            "rows": int(ds.get("Rows", 0)),
            "columns": int(ds.get("Columns", 0)),
            "samples_per_pixel": int(ds.get("SamplesPerPixel", 1)),
            "bits_allocated": int(ds.get("BitsAllocated", 0)),
            "pixel_representation": int(ds.get("PixelRepresentation", 0)),
            "photometric_interpretation": str(ds.get("PhotometricInterpretation", "")),
        }
    except Exception as exc:
        raise InferenceError(f"Cannot read DICOM header: {Path(path).name}.") from exc
    result["eligible"] = (
        MIN_FRAMES <= result["frames"] <= MAX_FRAMES
        and result["rows"] > 0 and result["columns"] > 0
        and result["samples_per_pixel"] == 1
        and result["bits_allocated"] in (8, 16)
        and result["pixel_representation"] == 0
        and result["photometric_interpretation"] in ("MONOCHROME1", "MONOCHROME2")
    )
    return result


def read_video(path):
    """Return raw unsigned grayscale frames; preserve the reference pixel convention."""
    import numpy as np
    import pydicom
    meta = inspect(path)
    if not meta["eligible"]:
        raise InferenceError(
            f"{Path(path).name}: use an unsigned 8/16-bit grayscale DICOM cine "
            f"with {MIN_FRAMES}–{MAX_FRAMES} frames."
        )
    if meta["frames"] * meta["rows"] * meta["columns"] * (meta["bits_allocated"] // 8) > MAX_DECODED_BYTES:
        raise InferenceError(f"{Path(path).name}: the decoded video exceeds the memory limit.")
    try:
        video = pydicom.dcmread(str(path)).pixel_array
    except Exception as exc:
        raise InferenceError(f"Cannot decode DICOM pixels: {Path(path).name}.") from exc
    if video.ndim != 3 or tuple(video.shape) != (meta["frames"], meta["rows"], meta["columns"]):
        raise InferenceError(f"{Path(path).name}: pixel dimensions do not match its DICOM header.")
    if video.dtype.kind != "u" or video.dtype.itemsize not in (1, 2):
        raise InferenceError(f"{Path(path).name}: unsupported pixel data type.")
    # Rescale/windowing and MONOCHROME1 inversion are deliberately not applied:
    # the published model reads pixel_array directly using these conventions.
    return np.asarray(video)


def validate_study(paths):
    """Reject mixed studies and duplicate acquisitions without reordering paths."""
    records = [inspect(path) for path in paths]
    if not records:
        raise InferenceError("Select at least one angiography projection.")
    if any(not record["study_uid"] or not record["sop_uid"] for record in records):
        raise InferenceError("Each DICOM must retain StudyInstanceUID and SOPInstanceUID.")
    if len({r["study_uid"] for r in records}) != 1:
        raise InferenceError("The selected projections belong to different studies.")
    if len({r["sop_uid"] for r in records}) != len(records):
        raise InferenceError("A projection is included more than once (duplicate SOPInstanceUID).")
    if any(not r["eligible"] for r in records):
        raise InferenceError("Remove unsupported or fewer-than-10-frame projections before inference.")
    return records