Exemplo n.º 1
0
def store_image(image: Image, all_image_files: Sequence[ImageFile]):
    """
    Stores an image in the database in a single transaction (or fails
    accordingly). Associated image files are extracted from the
    all_image_files argument and stored together with the image itself
    in a single transaction.

    Parameters
    ----------
    image: :class:`Image`
        The image to store. The actual image files that are stored are extracted
        from the second argument.

    all_image_files: list of :class:`ImageFile`
        An unordered list of ImageFile objects that might or might not belong
        to the image provided as the first argument. The function automatically
        extracts related images from the all_image_files argument to store
        alongside the given image.
    """
    associated_files = [
        _if for _if in all_image_files
        if _if.image == image
    ]
    image.save()
    for af in associated_files:
        af.save()
Exemplo n.º 2
0
def create_tiff_image_entry(*, tiff_file: GrandChallengeTiffFile) -> Image:
    # Builds a new Image model item
    return Image(
        name=tiff_file.path.name,
        width=tiff_file.tags.image_width,
        height=tiff_file.tags.image_height,
        depth=None,
        resolution_levels=tiff_file.tags.resolution_levels,
        color_space=tiff_file.tags.color_space,
    )
Exemplo n.º 3
0
def create_tiff_image_entry(*, tiff_file: GrandChallengeTiffFile) -> Image:
    # Builds a new Image model item
    return Image(
        name=tiff_file.path.name,
        width=tiff_file.tags.image_width,
        height=tiff_file.tags.image_height,
        depth=1,
        resolution_levels=tiff_file.tags.resolution_levels,
        color_space=tiff_file.tags.color_space,
        eye_choice=Image.EYE_UNKNOWN,
        stereoscopic_choice=Image.STEREOSCOPIC_UNKNOWN,
        field_of_view=Image.FOV_UNKNOWN,
    )
Exemplo n.º 4
0
def store_image(image: Image, all_image_files: Sequence[ImageFile]):
    """
    Stores an image in the database in a single transaction (or fails
    accordingly). Associated image files are extracted from the
    all_image_files argument and stored together with the image itself
    in a single transaction.

    Parameters
    ----------
    image: :class:`Image`
        The image to store. The actual image files that are stored are extracted
        from the second argument.

    all_image_files: list of :class:`ImageFile`
        An unordered list of ImageFile objects that might or might not belong
        to the image provided as the first argument. The function automatically
        extracts related images from the all_image_files argument to store
        alongside the given image.
    """
    associated_files = [_if for _if in all_image_files if _if.image == image]
    image.save()
    for af in associated_files:
        af.save()
Exemplo n.º 5
0
    def convert_itk_file(headers: Mapping[str, Union[str, None]],
                         filename: Path) -> Tuple[Image, Sequence[ImageFile]]:
        try:
            simple_itk_image = sitk.ReadImage(str(filename.absolute()))
            simple_itk_image: sitk.Image
        except RuntimeError:
            raise ValueError("SimpleITK cannot open file")

        color_space = simple_itk_image.GetNumberOfComponentsPerPixel()
        color_space = {
            1: Image.COLOR_SPACE_GRAY,
            3: Image.COLOR_SPACE_RGB,
            4: Image.COLOR_SPACE_RGBA,
        }.get(color_space, None)
        if color_space is None:
            raise ValueError("Unknown color space for MetaIO image.")

        with TemporaryDirectory() as work_dir:
            work_dir = Path(work_dir)

            sitk.WriteImage(simple_itk_image, str(work_dir / "out.mhd"), True)

            depth = simple_itk_image.GetDepth()
            db_image = Image(
                name=filename.name,
                width=simple_itk_image.GetWidth(),
                height=simple_itk_image.GetHeight(),
                depth=depth if depth else None,
                resolution_levels=None,
                color_space=color_space,
            )
            db_image_files = []
            for _file in work_dir.iterdir():
                temp_file = TemporaryFile()
                with open(_file, "rb") as open_file:
                    buffer = True
                    while buffer:
                        buffer = open_file.read(1024)
                        temp_file.write(buffer)

                db_image_file = ImageFile(
                    image=db_image,
                    image_type=ImageFile.IMAGE_TYPE_MHD,
                    file=File(temp_file, name=_file.name),
                )
                db_image_files.append(db_image_file)

        return db_image, db_image_files
def test_image_builder_dicom_4dct(tmpdir):
    files = {Path(d[0]).joinpath(f) for d in os.walk(DICOM_DIR) for f in d[2]}
    result = _build_files(builder=image_builder_dicom,
                          files=files,
                          output_directory=tmpdir)
    assert result.consumed_files == {
        Path(DICOM_DIR).joinpath(f"{x}.dcm")
        for x in range(1, 77)
    }

    assert len(result.new_images) == 1
    image = Image(**asdict(result.new_images.pop()))
    assert image.shape == [19, 4, 2, 3]
    assert len(result.new_image_files) == 1
    mha_file_obj = [
        x for x in result.new_image_files if x.file.suffix == ".mha"
    ][0]

    headers = parse_mh_header(mha_file_obj.file)

    direction = headers["TransformMatrix"].split()
    origin = headers["Offset"].split()
    spacing = headers["ElementSpacing"].split()
    exposures = headers["Exposures"].split()
    content_times = headers["ContentTimes"].split()

    assert len(exposures) == 19
    assert exposures == [str(x) for x in range(100, 2000, 100)]
    assert len(content_times) == 19
    assert content_times == [str(x) for x in range(214501, 214520)]

    dcm_ref = pydicom.dcmread(str(DICOM_DIR / "1.dcm"))
    assert np.array_equal(
        np.array(list(map(float, direction))).reshape((4, 4)), np.eye(4))
    assert np.allclose(
        list(map(float, spacing))[:2],
        list(map(
            float,
            list(dcm_ref.PixelSpacing),
        )),
    )
    assert np.allclose(
        list(map(float, origin)),
        list(map(float, dcm_ref.ImagePositionPatient)) + [0.0],
    )
Exemplo n.º 7
0
def _convert_panimg_to_django(*,
                              panimg_result: PanImgResult) -> ConversionResult:
    new_images = {Image(**asdict(im)) for im in panimg_result.new_images}
    new_image_files = {
        ImageFile(
            image_id=f.image_id,
            image_type=f.image_type,
            file=File(open(f.file, "rb"), f.file.name),
        )
        for f in panimg_result.new_image_files
    }
    new_folders = {
        FolderUpload(**asdict(f))
        for f in panimg_result.new_folders
    }

    return ConversionResult(
        new_images=new_images,
        new_image_files=new_image_files,
        new_folders=new_folders,
    )
def _create_algorithm_demo(users):
    cases_image = Image(
        name="test_image.mha",
        modality=ImagingModality.objects.get(modality="MR"),
        width=128,
        height=128,
        color_space="RGB",
    )
    cases_image.save()

    algorithm = Algorithm.objects.create(title="Test Algorithm",
                                         logo=create_uploaded_image())
    algorithm.editors_group.user_set.add(users["algorithm"], users["demo"])
    algorithm.users_group.user_set.add(users["algorithmuser"])
    algorithm.result_template = (
        "{% for key, value in results.metrics.items() -%}"
        "{{ key }}  {{ value }}"
        "{% endfor %}")
    detection_interface = ComponentInterface(
        store_in_database=False,
        relative_path="detection_results.json",
        slug="detection-results",
        title="Detection Results",
        kind=ComponentInterface.Kind.ANY,
    )
    detection_interface.save()
    algorithm.outputs.add(detection_interface)
    algorithm_image = AlgorithmImage(creator=users["algorithm"],
                                     algorithm=algorithm)

    if os.path.isfile(settings.DEMO_ALGORITHM_IMAGE_PATH):
        with open(settings.DEMO_ALGORITHM_IMAGE_PATH, "rb") as f:
            container = File(f)
            algorithm_image.image.save("test_algorithm.tar", container)
            algorithm_image.image_sha256 = settings.DEMO_ALGORITHM_SHA256
    else:
        container = ContentFile(base64.b64decode(b""))
        algorithm_image.image.save("test_algorithm.tar", container)

    algorithm_image.save()

    results = [
        {
            "cancer_score": 0.5
        },
        {
            "cancer_score": 0.6
        },
        {
            "cancer_score": 0.7
        },
    ]

    detections = [
        {
            "detected points": [{
                "type": "Point",
                "start": [0, 1, 2],
                "end": [3, 4, 5]
            }]
        },
        {
            "detected points": [{
                "type": "Point",
                "start": [6, 7, 8],
                "end": [9, 10, 11]
            }]
        },
        {
            "detected points": [{
                "type": "Point",
                "start": [12, 13, 14],
                "end": [15, 16, 17]
            }]
        },
    ]
    for res, det in zip(results, detections):
        _create_job_result(users, algorithm_image, cases_image, res, det)