Skip to content

Commit aef7177

Browse files
authored
bug: read zipped tiff
1 parent b7ced85 commit aef7177

File tree

1 file changed

+28
-6
lines changed

1 file changed

+28
-6
lines changed

src/segmentation_skeleton_metrics/utils/img_util.py

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
import io
1616
import numpy as np
17+
import os
1718
import tensorstore as ts
1819
import zipfile
1920

@@ -170,22 +171,22 @@ class TiffReader(ImageReader):
170171
Class that reads an image with the Tifffile library.
171172
"""
172173

173-
def __init__(self, img_path, inner_tiff_filename=None, swap_axes=True):
174+
def __init__(self, img_path, inner_tiff=None, swap_axes=True):
174175
"""
175176
Instantiates a TiffReader image reader.
176177
177178
Parameters
178179
----------
179180
img_path : str
180181
Path to a TIFF image or ZIP archive containing a TIFF image.
181-
inner_tiff_filename : str or None, optional
182+
inner_tiff : str or None, optional
182183
If img_path is a ZIP file, specifies the TIFF filename inside the
183184
ZIP. Default is None.
184185
swap_axes : bool, optional
185186
Indication of whether to swap axes 0 and 2. Default is True.
186187
"""
187188
# Instance attributes
188-
self.inner_tiff_filename = inner_tiff_filename
189+
self.inner_tiff = inner_tiff
189190
self.swap_axes = swap_axes
190191

191192
# Call parent class
@@ -197,16 +198,37 @@ def _load_image(self):
197198
"""
198199
# Read image
199200
if self.img_path.lower().endswith(".zip"):
200-
with zipfile.ZipFile(self.img_path, "r") as z:
201-
with z.open(self.inner_tiff_filename) as f:
202-
self.img = imread(io.BytesIO(f.read()))
201+
assert self.inner_tiff is not None, "Must provide TIFF filename!"
202+
self._load_zipped_image()
203203
else:
204204
self.img = imread(self.img_path)
205205

206206
# Swap axes (if applicable)
207207
if self.swap_axes:
208208
self.img = np.swapaxes(self.img, 0, 2)
209209

210+
def _load_zipped_image(self):
211+
"""
212+
Loads an image in a ZIP archive using the Tifffile library.
213+
"""
214+
with zipfile.ZipFile(self.img_path, "r") as z:
215+
# Collect only valid TIFF files, ignoring __MACOSX junk
216+
tiff_files = [
217+
f for f in z.namelist()
218+
if f.lower().endswith((".tif", ".tiff"))
219+
and not os.path.basename(f).startswith("._")
220+
]
221+
222+
# Choose file
223+
matches = [f for f in tiff_files if f.endswith(self.inner_tiff)]
224+
if not matches:
225+
raise FileNotFoundError(f"{self.inner_tiff} not found in ZIP")
226+
filename = matches[0]
227+
228+
# Load TIFF
229+
with z.open(filename) as f:
230+
self.img = imread(io.BytesIO(f.read()))
231+
210232

211233
# --- Miscellaneous ---
212234
def to_physical(voxel, anisotropy):

0 commit comments

Comments
 (0)