Export 3D multi-point ROI via roifile python library

I’m trying to export multi-point ROI via roifile library. The ROI should preserve the z-stacks information of the points also, like the ones generated by ImageJ itself. For this I tried assigning the z-stack values to roifile.ImagejRoi().counter_positions, but still at best I am only able to get 2D multi-point ROIs.

Comparing the attributes of ImageJ exported multi-point ROI and one generated by roifile, the only difference I was able to see was in roifile.ImagejRoi().subpixelrect and roifile.ImagejRoi().subpixelresolution.

@cgohlke could you help me with this?

This seems to work for me:

import numpy
import tifffile
import roifile


points_xy = numpy.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]])
points_z = numpy.array([1, 2, 3, 4, 5, 6])

n_coordinates = points_xy.shape[0]
left, top = points_xy.min(axis=0)
right, bottom = points_xy.max(axis=0)

roi = roifile.ImagejRoi()
roi.version = 227
roi.roitype = roifile.ROI_TYPE(10)
roi.n_coordinates = n_coordinates
roi.left = int(left)
roi.top = int(top)
roi.right = int(right)
roi.bottom = int(bottom)
roi.integer_coordinates = points_xy - [int(left), int(top)]
roi.counters = numpy.array([0] * n_coordinates)
roi.counter_positions = points_z

tifffile.imwrite(
    'test_multipoint.tif',
    numpy.zeros((6, 14, 13), dtype=numpy.uint8),
    imagej=True,
    metadata={'axes': 'ZYX', 'Overlays': roi.tobytes()},
)

There are many pitfalls, for example unlike in numpy convention the point coordinates are expected in column-row order and the counter_positions are one-based because zero seems to have a special meaning…

1 Like

Thanks @cgohlke
After loading these ROI in ImageJ, they appear to be very small and indiscernible. I have to manually edit the point properties via point tool each time I load it for new image. Can I set the color and size properties of these markers? I tried modifying some attributes but failed.

Try to set some additional properties, e.g.:

roi.arrow_style_or_aspect_ratio = 3
roi.stroke_width = 5
roi.stroke_color = b'\xFF\xFF\x00\x00'  # red

Since the ROI format is undocumented, you’ll have to check the ImageJ source code or study ROI’s with known properties created by ImageJ. Roifile can print the non-default properties of ROIs:

python -m roifile name_of_roi_or_tiff_file
1 Like