Source code for ktch.io._roi

"""ImageJ ROI file I/O functions."""

# Copyright 2026 Koji Noshita
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import struct
import zipfile
from dataclasses import dataclass
from pathlib import Path, PurePosixPath

import numpy as np
import pandas as pd

from ._protocols import MorphoDataMixin

# The layout follows ImageJ's ij/io/RoiDecoder.java. Every field is big-endian.
_MAGIC = b"Iout"
_HEADER_SIZE = 64
_HEADER2_SIZE = 64

_TYPE_NAMES = {
    0: "polygon",
    1: "rect",
    2: "oval",
    3: "line",
    4: "freeline",
    5: "polyline",
    6: "noRoi",
    7: "freehand",
    8: "traced",
    9: "angle",
    10: "point",
}
# The types that store a list of coordinates.
_COORDINATE_TYPES = (
    "polygon",
    "freehand",
    "traced",
    "polyline",
    "freeline",
    "angle",
    "point",
)
# Subtypes that replace the coordinate list with parameters of a shape.
_SUBTYPE_NAMES = {
    1: "text",
    2: "arrow",
    3: "ellipse",
    4: "image",
    5: "rotated rectangle",
}

_TYPE_CODES = {name: code for code, name in _TYPE_NAMES.items()}

_SPLINE_FIT = 1
_SUB_PIXEL_RESOLUTION = 128
# Sub-pixel coordinates are stored from this version on.
_SUB_PIXEL_VERSION = 222
# The version write_roi writes: every field it fills exists from it on.
_WRITE_VERSION = 228
# The range of a 16-bit coordinate that ImageJ reads back unchanged.
_SHORT_RANGE = (-5000, 60535)
# The largest count stored in 16 bits; only point ROIs store a larger one.
_MAX_COUNT = 65535


[docs] @dataclass(repr=False) class RoiData(MorphoDataMixin): """One ImageJ region of interest (ROI) with a list of coordinates. ImageJ and Fiji save a selection as a ``.roi`` file, and the ROI Manager saves a set of them as a ``.zip`` of ``.roi`` files. Other programs, such as cell-tracking software, export outlines in the same format. Attributes ---------- specimen_name : str The name of the ``.roi`` file, or of its entry in a ROI set, without the ``.roi`` suffix. It is unique within a ROI set. coords : ndarray of shape (n_coords, 2) The coordinates as the file stores them, in pixels: x to the right and y downward from the top-left of the image. A closed outline does not repeat its first point. roi_type : str ``"polygon"``, ``"freehand"`` or ``"traced"`` for a closed outline, ``"polyline"`` or ``"freeline"`` for an open curve, ``"angle"`` for the three points of an angle, or ``"point"`` for points. name : str or None The name stored in the ROI, if any. Cell-tracking software, for example, can store the identifier of a tracked object here. position : int or None The position in an image stack (1-based), if stored. channel, slice, frame : int or None The channel, slice and frame of a hyperstack (1-based), if stored. subpixel : bool Whether the file stores sub-pixel (floating-point) coordinates. spline_fit : bool Whether ImageJ fits a spline through the coordinates when it shows the ROI. The coordinates are then the control points. Notes ----- Which point of a pixel an integer coordinate refers to depends on the program that wrote the file. ImageJ places the integer coordinates of an area ROI (polygon, freehand, traced) at the top-left corner of a pixel, and those of line and point ROIs at its centre. OpenCV's drawing functions and :func:`matplotlib.pyplot.imshow` place integer coordinates at pixel centres. An outline that ImageJ's wand tool traced along pixel edges is therefore drawn by those libraries half a pixel down and to the right of the edges it follows: subtract 0.5 from its coordinates to overlay it. Outlines that list their boundary pixels, as ``cv2.findContours`` does, need no shift. """ specimen_name: str coords: np.ndarray roi_type: str = "polygon" name: str | None = None position: int | None = None channel: int | None = None slice: int | None = None frame: int | None = None subpixel: bool = False spline_fit: bool = False def __post_init__(self): if self.roi_type not in _COORDINATE_TYPES: raise ValueError( f"roi_type must be one of {_COORDINATE_TYPES}, got {self.roi_type!r}" ) coords = np.asarray(self.coords, dtype=float) if coords.ndim != 2 or coords.shape[1] != 2: raise ValueError( f"coords must have shape (n_coords, 2); got {coords.shape}" ) self.coords = coords def _repr_detail(self): return f"roi_type={self.roi_type!r}, n_coords={len(self.coords)}"
[docs] def to_numpy(self): """Return the coordinates. Returns ------- coords : ndarray of shape (n_coords, 2) The x and y coordinates. """ return self.coords
[docs] def to_dataframe(self): """Return the coordinates as a DataFrame. Returns ------- df : pd.DataFrame Columns ``x``, ``y``, ``name`` and ``position``. Index is a MultiIndex ``(specimen_id, coord_id)``. """ return _to_frame([self])
[docs] def read_roi(file_path, as_frame=False): """Read an ImageJ ROI file (.roi) or ROI set (.zip). Reads the ROI types that store a list of coordinates: closed outlines (polygon, freehand, traced), open curves (polyline, freeline), angles and points. The coordinates are returned as the file stores them, in pixels with y downward (see :class:`RoiData` for where an integer coordinate lies in a pixel). Parameters ---------- file_path : str or pathlib.Path Path to a ``.roi`` file, or to a ``.zip`` of ``.roi`` files such as the ROI Manager saves. Entries of the ``.zip`` that are not ``.roi`` files are skipped. as_frame : bool, default=False If True, return a :class:`~pandas.DataFrame`. Returns ------- result : RoiData or list of RoiData or pd.DataFrame A :class:`RoiData` for a single ROI, a list of them, in the order of the ROI set, for several, or, with ``as_frame=True``, one DataFrame with columns ``x``, ``y``, ``name`` and ``position`` and a MultiIndex ``(specimen_id, coord_id)``. Raises ------ FileNotFoundError If the file does not exist. ValueError If the file is not a ``.roi`` or ``.zip`` file, if a ROI set holds no ``.roi`` file, if a ROI is not in the ImageJ format or is truncated, or if a ROI is of a type without a coordinate list (rectangle, oval, straight line, composite, text, image, or a freehand ellipse or rotated rectangle). The message names the ROI. Examples -------- >>> from ktch.io import read_roi >>> rois = read_roi("RoiSet.zip") # doctest: +SKIP >>> rois[0].coords # doctest: +SKIP """ path = Path(file_path) if not path.exists(): raise FileNotFoundError(f"{path} does not exist.") suffix = path.suffix.lower() if suffix == ".roi": rois = [_decode(path.read_bytes(), path.stem, str(path))] elif suffix == ".zip": with zipfile.ZipFile(path) as zf: entries = [ info for info in zf.infolist() if not info.is_dir() and info.filename.lower().endswith(".roi") ] if not entries: raise ValueError(f"{path} holds no .roi file.") rois = [ _decode( zf.read(info), PurePosixPath(info.filename).stem, f"{path}:{info.filename}", ) for info in entries ] else: raise ValueError(f"{path} is not an ImageJ ROI file (.roi) or ROI set (.zip).") if as_frame: return _to_frame(rois) if len(rois) == 1: return rois[0] return rois
[docs] def write_roi( file_path, coords, roi_type="polygon", specimen_names=None, names=None, positions=None, ): """Write an ImageJ ROI file (.roi) or ROI set (.zip). Writes the ROI types that store a list of coordinates, in the format ImageJ and Fiji read. Coordinates that are all integers are stored as integers; otherwise ImageJ's sub-pixel coordinates are written too. Parameters ---------- file_path : str or pathlib.Path A ``.roi`` path for one ROI, or a ``.zip`` path for a ROI set. coords : array-like, list of array-like, RoiData or list of RoiData The coordinates of each ROI, in pixels with y downward (see :class:`RoiData`). A 2-D array of shape ``(n_coords, 2)`` is one ROI; a 3-D array or a list holds one per ROI. A :class:`RoiData`, such as :func:`read_roi` returns, carries its own type, names, stack position and flags; the other arguments must then be left out. roi_type : str or list of str, default="polygon" ``"polygon"``, ``"freehand"`` or ``"traced"`` for a closed outline, ``"polyline"`` or ``"freeline"`` for an open curve, ``"angle"`` or ``"point"``. One value applies to every ROI. specimen_names : str or list of str, optional The names of the entries of a ROI set, without ``.roi``. They must be unique. Defaults to ``"0"``, ``"1"``, ... A ``.roi`` file takes its name from ``file_path``. names : str or list of str, optional The names stored in the ROIs. positions : int or list of int, optional The positions in an image stack (1-based). Raises ------ ValueError If ``file_path`` is not a ``.roi`` or ``.zip`` path, if a ``.roi`` path is given several ROIs, if the lengths of the arguments do not match, if entry names repeat, if a ROI has no coordinates, if a ROI other than a point ROI has more than 65535 coordinates, or if a coordinate lies outside the range ImageJ stores (-5000 to 60535). See Also -------- read_roi : Read an ImageJ ROI file or ROI set. Examples -------- >>> import numpy as np >>> from ktch.io import write_roi >>> square = np.array([[10, 20], [14, 20], [14, 25], [10, 25]]) >>> write_roi("square.roi", square, names="square") # doctest: +SKIP """ path = Path(file_path) suffix = path.suffix.lower() if suffix not in (".roi", ".zip"): raise ValueError(f"{path} is not an ImageJ ROI file (.roi) or ROI set (.zip).") rois = _rois_to_write(coords, roi_type, specimen_names, names, positions) if suffix == ".roi": if len(rois) != 1: raise ValueError( f"{path} is a single ROI file; write {len(rois)} ROIs to a .zip." ) path.write_bytes(_encode(rois[0])) return entry_names = [roi.specimen_name for roi in rois] if len(set(entry_names)) != len(entry_names): repeated = sorted({n for n in entry_names if entry_names.count(n) > 1}) raise ValueError(f"The entry names of a ROI set must be unique: {repeated}") with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED) as zf: for roi in rois: zf.writestr(f"{roi.specimen_name}.roi", _encode(roi))
def _rois_to_write(coords, roi_type, specimen_names, names, positions): """The :class:`RoiData` that ``write_roi`` writes.""" if isinstance(coords, RoiData) or ( isinstance(coords, list) and coords and isinstance(coords[0], RoiData) ): if not ( roi_type == "polygon" and specimen_names is None and names is None and positions is None ): raise ValueError( "RoiData carries its own type, names and position; leave out " "roi_type, specimen_names, names and positions." ) return [coords] if isinstance(coords, RoiData) else list(coords) if isinstance(coords, np.ndarray) and coords.ndim == 2: coords_list = [coords] elif isinstance(coords, np.ndarray) and coords.ndim == 3: coords_list = list(coords) elif isinstance(coords, (list, tuple)): coords_list = list(coords) else: raise ValueError( "coords must be a 2-D or 3-D array, a list of 2-D arrays, a RoiData " "or a list of RoiData." ) n_rois = len(coords_list) def per_roi(value, arg_name, default, broadcast=True): if value is None: return [default(i) for i in range(n_rois)] if isinstance(value, (str, int, np.integer)): # One entry name cannot serve several ROIs. value = [value] * (n_rois if broadcast else 1) else: value = list(value) if len(value) != n_rois: raise ValueError( f"Length of {arg_name} ({len(value)}) does not match the number " f"of ROIs ({n_rois})." ) return value types = per_roi(roi_type, "roi_type", lambda i: "polygon") entries = per_roi(specimen_names, "specimen_names", str, broadcast=False) return [ RoiData( specimen_name=str(entry), coords=c, roi_type=t, name=name, position=position, ) for c, t, entry, name, position in zip( coords_list, types, entries, per_roi(names, "names", lambda i: None), per_roi(positions, "positions", lambda i: None), ) ] def _encode(roi): """The bytes of a ``.roi`` file holding ``roi``.""" coords = roi.coords n_coords = len(coords) label = f"ROI {roi.specimen_name!r}" if n_coords == 0: raise ValueError(f"{label} has no coordinates.") if n_coords > _MAX_COUNT and roi.roi_type != "point": raise ValueError( f"{label} has {n_coords} coordinates; ImageJ stores at most " f"{_MAX_COUNT} for a {roi.roi_type} ROI." ) subpixel = roi.subpixel or not np.array_equal(coords, np.round(coords)) lower = np.floor(coords.min(axis=0)).astype(int) upper = np.ceil(coords.max(axis=0)).astype(int) # The bounds and the coordinates relative to them are 16-bit values. if ( lower.min() < _SHORT_RANGE[0] or upper.max() > _SHORT_RANGE[1] or (upper - lower).max() > _SHORT_RANGE[1] ): raise ValueError( f"{label} has coordinates outside the range ImageJ stores " f"({_SHORT_RANGE[0]} to {_SHORT_RANGE[1]})." ) left, top = lower right, bottom = upper header = bytearray(_HEADER_SIZE) header[0:4] = _MAGIC struct.pack_into(">h", header, 4, _WRITE_VERSION) header[6] = _TYPE_CODES[roi.roi_type] # ImageJ reads 16-bit values above 32767 back unsigned. struct.pack_into( ">HHHH", header, 8, *(int(v) & 0xFFFF for v in (top, left, bottom, right)) ) if n_coords > _MAX_COUNT: struct.pack_into(">i", header, 18, n_coords) else: struct.pack_into(">H", header, 16, n_coords) options = (_SUB_PIXEL_RESOLUTION if subpixel else 0) | ( _SPLINE_FIT if roi.spline_fit else 0 ) struct.pack_into(">h", header, 50, options) struct.pack_into(">i", header, 56, roi.position or 0) relative = np.round(coords).astype(np.int64) - (left, top) body = (relative.T & 0xFFFF).astype(">u2").tobytes() if subpixel: body += coords.T.astype(">f4").tobytes() header2_offset = _HEADER_SIZE + len(body) struct.pack_into(">i", header, 60, header2_offset) header2 = bytearray(_HEADER2_SIZE) struct.pack_into( ">iii", header2, 4, roi.channel or 0, roi.slice or 0, roi.frame or 0 ) name = b"" if roi.name: name = roi.name.encode("utf-16-be") struct.pack_into( ">ii", header2, 16, header2_offset + _HEADER2_SIZE, len(name) // 2 ) return bytes(header) + body + bytes(header2) + name def _short(values): """Signed 16-bit values, as ImageJ's ``RoiDecoder.getShort`` reads them. A value below -5000 is taken to be an unsigned value above 32767. """ values = np.asarray(values, dtype=np.int64) return np.where(values < -5000, values + 65536, values) def _decode(data, specimen_name, source): """Decode the bytes of one ``.roi`` file into a :class:`RoiData`.""" if len(data) < _HEADER_SIZE or data[:4] != _MAGIC: raise ValueError(f"{source} is not an ImageJ ROI.") (version,) = struct.unpack(">h", data[4:6]) type_code = data[6] top, left = (int(v) for v in _short(struct.unpack(">hh", data[8:12]))) (n_coords,) = struct.unpack(">H", data[16:18]) (shape_length,) = struct.unpack(">i", data[36:40]) subtype, options = struct.unpack(">hh", data[48:52]) position, header2_offset = struct.unpack(">ii", data[56:64]) roi_type = _TYPE_NAMES.get(type_code, f"unknown ({type_code})") if shape_length > 0: roi_type = "composite" elif roi_type == "freehand" and subtype in _SUBTYPE_NAMES: roi_type = f"freehand {_SUBTYPE_NAMES[subtype]}" if roi_type not in _COORDINATE_TYPES: raise ValueError( f"{source}: a {roi_type} ROI has no coordinate list; read_roi reads " f"the types {', '.join(_COORDINATE_TYPES)}." ) if n_coords == 0: # A count above 65535 is stored as a 32-bit integer. (n_coords,) = struct.unpack(">i", data[18:22]) subpixel = bool(options & _SUB_PIXEL_RESOLUTION) and version >= _SUB_PIXEL_VERSION end = _HEADER_SIZE + (12 if subpixel else 4) * n_coords if n_coords < 0 or end > len(data): raise ValueError(f"{source} is truncated.") base = _HEADER_SIZE if subpixel: # The floats follow the integers and are absolute coordinates. base += 4 * n_coords x = np.frombuffer(data, ">f4", n_coords, base) y = np.frombuffer(data, ">f4", n_coords, base + 4 * n_coords) else: # The integers are relative to the left and top of the bounding box. x = left + _short(np.frombuffer(data, ">i2", n_coords, base)) y = top + _short(np.frombuffer(data, ">i2", n_coords, base + 2 * n_coords)) coords = np.column_stack([x, y]).astype(float) name = channel = slice_ = frame = None if 0 < header2_offset and header2_offset + _HEADER2_SIZE <= len(data): channel, slice_, frame = ( v or None for v in struct.unpack( ">iii", data[header2_offset + 4 : header2_offset + 16] ) ) name_offset, name_length = struct.unpack( ">ii", data[header2_offset + 16 : header2_offset + 24] ) if 0 < name_offset and 0 < name_length: name_end = name_offset + 2 * name_length if name_end <= len(data): name = data[name_offset:name_end].decode("utf-16-be") return RoiData( specimen_name=specimen_name, coords=coords, roi_type=roi_type, name=name, position=position or None, channel=channel, slice=slice_, frame=frame, subpixel=subpixel, spline_fit=bool(options & _SPLINE_FIT), ) def _to_frame(rois): """One DataFrame of the coordinates of ``rois``.""" counts = [len(roi.coords) for roi in rois] coords = np.concatenate([roi.coords for roi in rois]) index = pd.MultiIndex.from_arrays( [ np.repeat( np.array([roi.specimen_name for roi in rois], dtype=object), counts ), np.concatenate([np.arange(n) for n in counts]), ], names=["specimen_id", "coord_id"], ) return pd.DataFrame( { "x": coords[:, 0], "y": coords[:, 1], "name": np.repeat( np.array([roi.name for roi in rois], dtype=object), counts ), "position": pd.array( np.repeat( np.array([roi.position for roi in rois], dtype=object), counts ), dtype="Int64", ), }, index=index, )