Skip to content

Commit b5b1eff

Browse files
committed
fix(img2tensorboard): correct GIF header byte sequence and add error handling for video writing
Signed-off-by: R. Garcia-Dias <rafaelagd@gmail.com>
1 parent 0a90770 commit b5b1eff

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

monai/visualize/img2tensorboard.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ def _image3_animated_gif(
6565
img_str = b""
6666
for b_data in PIL.GifImagePlugin.getheader(ims[0])[0]:
6767
img_str += b_data
68-
img_str += b"\x21\xff\x0b\x4e\x45\x54\x53\x43\x41\x50" b"\x45\x32\x2e\x30\x03\x01\x00\x00\x00"
68+
img_str += b"\x21\xff\x0b\x4e\x45\x54\x53\x43\x41\x50\x45\x32\x2e\x30\x03\x01\x00\x00\x00"
6969
for i in ims:
7070
for b_data in PIL.GifImagePlugin.getdata(i):
7171
img_str += b_data
@@ -204,8 +204,17 @@ def plot_2d_or_3d_image(
204204
if d_chans == 3 and max_channels == 3 and has_tensorboardx and isinstance(writer, SummaryWriterX): # RGB
205205
# move the expected frame dim to the end as `T` dim for video
206206
d = np.moveaxis(d, frame_dim, -1)
207-
writer.add_video(tag, d[None], step, fps=max_frames, dataformats="NCHWT")
208-
return
207+
try:
208+
writer.add_video(tag, d[None], step, fps=max_frames, dataformats="NCHWT")
209+
return
210+
except TypeError as e:
211+
# Fallback for numpy 2.x incompatibility in tensorboardX
212+
# (https://github.com/lanpa/tensorboardX/issues/XXX)
213+
# tensorboardX uses np.reshape(..., newshape=...) which is not supported in numpy 2.0+
214+
if "newshape" in str(e):
215+
pass # Fall through to animated GIF approach
216+
else:
217+
raise
209218
# scale data to 0 - 255 for visualization
210219
max_channels = min(max_channels, d_chans)
211220
d = np.stack([rescale_array(i, 0, 255) for i in d[:max_channels]], axis=0)

0 commit comments

Comments
 (0)