Skip to content

Commit

Permalink
calc mpp with openslide tiff tags (#166)
Browse files Browse the repository at this point in the history
  • Loading branch information
kaczmarj authored Jul 24, 2023
1 parent 0338d76 commit 8dbb90f
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
11 changes: 9 additions & 2 deletions tests/test_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,8 +293,13 @@ def test_convert_to_sbu():
["patch_size", "patch_spacing"],
[(256, 0.25), (256, 0.50), (350, 0.25), (100, 0.3), (100, 0.5)],
)
@pytest.mark.parametrize("backend", ["openslide", "tiffslide"])
def test_patch_cli(
patch_size: int, patch_spacing: float, tmp_path: Path, tiff_image: Path
patch_size: int,
patch_spacing: float,
backend: str,
tmp_path: Path,
tiff_image: Path,
):
"""Test of 'wsinfer patch'."""
orig_slide_size = 4096
Expand All @@ -305,6 +310,8 @@ def test_patch_cli(
result = runner.invoke(
cli,
[
"--backend",
backend,
"patch",
"--wsi-dir",
str(tiff_image.parent),
Expand Down Expand Up @@ -342,7 +349,7 @@ def test_patch_cli(
assert np.array_equal(expected_coords, coords)


# FIXME: parametrize thie test across our models.
# FIXME: parametrize this test across our models.
def test_jit_compile():
w = get_registered_model("breast-tumor-resnet34.tcga-brca")
model = get_pretrained_torch_module(w)
Expand Down
32 changes: 32 additions & 0 deletions wsinfer/wsi.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,38 @@ def _get_mpp_openslide(slide_path: str | Path) -> tuple[float, float]:
return mppx, mppy
except Exception as err:
logger.debug(f"Exception caught while converting to float: {err}")
elif (
"tiff.ResolutionUnit" in slide.properties
and "tiff.XResolution" in slide.properties
and "tiff.YResolution" in slide.properties
):
logger.debug("Attempting to read spacing using openslide and tiff tags")
resunit = slide.properties["tiff.ResolutionUnit"].lower()
if resunit not in {"millimeter", "centimeter", "cm", "inch"}:
raise CannotReadSpacing(f"unknown resolution unit: '{resunit}'")
scale = {
"inch": 25400.0,
"centimeter": 10000.0,
"cm": 10000.0,
"millimeter": 1000.0,
}.get(resunit, None)

x_resolution = float(slide.properties["tiff.XResolution"])
y_resolution = float(slide.properties["tiff.YResolution"])

if scale is not None:
try:
mpp_x = scale / x_resolution
mpp_y = scale / y_resolution
return mpp_x, mpp_y
except ArithmeticError as err:
raise CannotReadSpacing(
f"error in math {scale} / {x_resolution}"
f" or {scale} / {y_resolution}"
) from err
else:
raise CannotReadSpacing()

else:
logger.debug(
"Properties of the OpenSlide object does not contain keys"
Expand Down

0 comments on commit 8dbb90f

Please sign in to comment.