.ipynb

Load ImageJ ROI files#

ImageJ/Fiji saves a selection as a .roi file, and the ROI Manager saves several of them as a .zip ROI set. Several cell-tracking software programs also export outlines in this format. read_roi() reads the ROIs that store a list of coordinates (outlines, open curves and points), and write_roi() writes them.

Make a sample ROI set#

In this guide, we generate the ROI set from the outlines of two blobs in an image using OpenCV.

import tempfile
from pathlib import Path

import cv2
import matplotlib.pyplot as plt
import numpy as np

from ktch.io import read_roi, write_roi

image = np.zeros((60, 90), dtype=np.uint8)
cv2.ellipse(image, (25, 30), (16, 9), 30, 0, 360, 255, -1)
cv2.circle(image, (36, 38), 6, 255, -1)
cv2.fillPoly(image, [np.array([[55, 15], [80, 20], [76, 45], [60, 42]])], 255)

contours, _ = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
outlines = [contour[:, 0, :] for contour in contours]

roi_set = Path(tempfile.mkdtemp()) / "RoiSet.zip"
write_roi(
    roi_set,
    outlines,
    roi_type="traced",
    specimen_names=["1-1", "1-2"],
    names=["1", "2"],
    positions=1,
)

Read the ROIs#

rois = read_roi(roi_set)
rois
[RoiData(specimen_name='1-1', roi_type='traced', n_coords=77),
 RoiData(specimen_name='1-2', roi_type='traced', n_coords=93)]

Each RoiData holds the coordinates, the ROI type, and the name and stack position the ROI stores. Tracking software, for example, stores the identifier of a cell as the name and its frame as the position.

roi = rois[0]
roi.coords[:5], roi.name, roi.position
(array([[14., 19.],
        [13., 20.],
        [12., 21.],
        [11., 22.],
        [11., 23.]]),
 '1',
 1)

With as_frame=True, the coordinates of every ROI come as one DataFrame, indexed by the entry name in the set and the coordinate number:

df = read_roi(roi_set, as_frame=True)
df.head()
x y name position
specimen_id coord_id
1-1 0 14.0 19.0 1 1
1 13.0 20.0 1 1
2 12.0 21.0 1 1
3 11.0 22.0 1 1
4 11.0 23.0 1 1

Overlay the outlines on the image#

The coordinates are returned as the file stores them, in pixels with y downward. matplotlib and OpenCV place integer coordinates at pixel centres. Outlines that list their boundary pixels, as these do, therefore overlay without a shift:

fig, ax = plt.subplots()
ax.imshow(image, cmap="gray")
for roi in rois:
    closed = np.vstack([roi.coords, roi.coords[:1]])
    ax.plot(closed[:, 0], closed[:, 1])
ax.set_axis_off()
../../../_images/0c812d2bcb68594ac3219df40f60e3507012096056221c9f6c93cb7ea529a3be.png

ImageJ places the integer coordinates of an area ROI at the top-left corner of a pixel. An outline traced in ImageJ with the wand tool follows pixel edges: subtract 0.5 from its coordinates before overlaying it this way.

Analyse the outlines#

The coordinates go to the analysis classes as they are:

from ktch.harmonic import EllipticFourierAnalysis

efa = EllipticFourierAnalysis(n_harmonics=10)
coef = efa.fit_transform([roi.coords for roi in rois])
coef.shape
(2, 44)

Write ROIs#

write_roi() writes one ROI to a .roi file, or several to a .zip ROI set. It takes coordinate arrays, or the RoiData that read_roi() returns:

single = roi_set.with_name("blob.roi")
write_roi(single, rois[0])
read_roi(single)
RoiData(specimen_name='blob', roi_type='traced', n_coords=77)

Coordinates that are not all integers are written with ImageJ’s sub-pixel resolution.

See also