|
| 1 | +"""ImageJ .roi file exporter.""" |
| 2 | + |
| 3 | +from pathlib import Path |
| 4 | +from typing import Union, List, Tuple |
| 5 | + |
| 6 | +from roifile import ImagejRoi, ROI_TYPE |
| 7 | + |
| 8 | +from PyReconstruct.modules.datatypes import Trace |
| 9 | + |
| 10 | + |
| 11 | +coordinates = List[Tuple[float, float]] |
| 12 | +filepath = Union[str, Path] |
| 13 | + |
| 14 | + |
| 15 | +class RoiExporter: |
| 16 | + |
| 17 | + def __init__(self, trace: Trace, mag: float, img_height: int): |
| 18 | + |
| 19 | + self.trace = trace |
| 20 | + self.coords = self.get_coords(mag, img_height) |
| 21 | + self.roi = self.get_roi() |
| 22 | + |
| 23 | + def export_roi(self, directory: filepath) -> None: |
| 24 | + """Export an ImageJ .roi file to a directory.""" |
| 25 | + |
| 26 | + if not isinstance(directory, Path): |
| 27 | + directory = Path(directory) |
| 28 | + |
| 29 | + ## Assume each trace uniquely named for now |
| 30 | + output_fp = directory / f"{self.trace.name}-exported.roi" |
| 31 | + |
| 32 | + self.roi.tofile(output_fp) |
| 33 | + |
| 34 | + return None |
| 35 | + |
| 36 | + def get_roi(self) -> ImagejRoi: |
| 37 | + """Get an ImageJ roi object.""" |
| 38 | + |
| 39 | + roi = ImagejRoi.frompoints(self.coords) |
| 40 | + |
| 41 | + roi.roitype = ROI_TYPE.POLYGON if self.trace.closed else ROI_TYPE.FREEHAND |
| 42 | + roi.name = self.trace.name |
| 43 | + |
| 44 | + return roi |
| 45 | + |
| 46 | + def get_coords(self, mag, img_height) -> coordinates: |
| 47 | + """Get coordinates as pixels.""" |
| 48 | + |
| 49 | + coords = self.trace.asPixels(mag, img_height, subpix=True) |
| 50 | + |
| 51 | + return [ |
| 52 | + (round(x, 3), round(y, 3)) for x, y in coords |
| 53 | + ] |
| 54 | + |
0 commit comments