Skip to content

Commit cc9d63f

Browse files
authored
Merge pull request #1406 from tlambert03/fix-nd2
fix nd2 reading on drop event
2 parents 5efc56c + f2e2950 commit cc9d63f

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

cellpose/gui/io.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ def _load_image(parent, filename=None, load_seg=True, load_3D=False):
139139
except Exception as e:
140140
print("ERROR: images not compatible")
141141
print(f"ERROR: {e}")
142+
return
142143

143144
if parent.loaded:
144145
parent.reset()

cellpose/io.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,28 @@ def imread(filename):
216216
if not ND2:
217217
io_logger.critical("ERROR: need to 'pip install nd2' to load in .nd2 file")
218218
return None
219+
else:
220+
with nd2.ND2File(filename) as nd2_file:
221+
img = nd2_file.asarray()
222+
sizes = nd2_file.sizes
223+
224+
kept_axes = [nd2.AXIS.Y, nd2.AXIS.X, nd2.AXIS.CHANNEL, nd2.AXIS.Z]
225+
# For multi-dimensional data (T, P, etc.), take first frame/position
226+
# Work backwards through axes to avoid index shifting
227+
for i, (ax_name, size) in reversed(list(enumerate(sizes.items()))):
228+
# Keep Y, X, C, Z; remove or reduce everything else
229+
if ax_name not in kept_axes:
230+
if size > 1:
231+
io_logger.warning(
232+
f"ND2 file has {size} {ax_name} - using first only"
233+
)
234+
# Take first element (works for both size=1 and size>1)
235+
img = np.take(img, 0, axis=i)
236+
237+
# Result should now be YX, CYX, ZYX, or CZYX depending on original axes
238+
# nd2 preserves axis order from sizes dict (usually C, Z, Y, X)
239+
return img
240+
219241
elif ext == ".nrrd":
220242
if not NRRD:
221243
io_logger.critical(
@@ -257,6 +279,8 @@ def imread_2D(img_file):
257279
img_out (numpy.ndarray): The 3-channel image data as a NumPy array.
258280
"""
259281
img = imread(img_file)
282+
if img is None:
283+
raise ValueError(f"could not read image file {img_file}")
260284
return transforms.convert_image(img, do_3D=False)
261285

262286

@@ -278,6 +302,8 @@ def imread_3D(img_file):
278302
img_out (numpy.ndarray): The image data as a NumPy array with channels last, or None if loading fails.
279303
"""
280304
img = imread(img_file)
305+
if img is None:
306+
raise ValueError(f"could not read image file {img_file}")
281307

282308
dimension_lengths = list(img.shape)
283309

0 commit comments

Comments
 (0)