Coverage for collectra/types/images.py: 82.47%
445 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
1"""Image handling and processing classes for the Collectra system.
3This module provides the core image classes used throughout Collectra for
4handling image data, metadata, and cropping operations. It supports various
5image formats and provides utilities for encoding, metadata extraction,
6and coordinate-based cropping.
8The module includes:
9 - Base Image class for general image handling
10 - ImageCrop class for coordinate-based image cropping
11 - Image format validation and metadata extraction
12 - Base64 encoding for image serialization
14Classes:
15 Image: Base class for image handling and metadata
16 ImageCrop: Specialized class for cropped image regions
17"""
19__all__ = ["Image", "ImageCrop", "ImageSegmentation"]
22import base64
23import io
24import shutil
25from enum import Enum
26from functools import lru_cache
27from pathlib import Path
28from typing import Any, ClassVar
30from PIL import Image as ImagePil
31from PIL import ImageOps
32from pydantic import Field, PrivateAttr, field_validator
34from collectra.cli import command
36from .base import Artefact, ArtefactCommands, ArtefactNode
39def _tiff_dimensions(path: str | Path) -> tuple[int, int, int]:
40 """Return width, height, channels from TIFF headers, without decoding pixels.
42 C/S denote channels/samples; I/Q denotes an otherwise unlabelled page stack.
43 Non-singleton time/depth axes and multiple image series are ambiguous for a
44 2D detector and must be exported as separate images first.
45 """
46 from tifffile import TiffFile
48 with TiffFile(path) as tiff:
49 if len(tiff.series) != 1:
50 raise ValueError(f"TIFF {path} contains multiple image series")
51 series = tiff.series[0]
52 shape, axes = series.shape, series.axes
53 if len(axes) != len(shape) or axes.count("Y") != 1 or axes.count("X") != 1:
54 raise ValueError(
55 f"Cannot identify TIFF spatial axes for {path}: shape={shape}, axes={axes!r}"
56 )
57 extra = [
58 (axis, size)
59 for axis, size in zip(axes, shape)
60 if axis not in "YX" and size != 1
61 ]
62 if len(extra) > 1 or (extra and extra[0][0] not in "CSIQ"):
63 raise ValueError(
64 f"Ambiguous TIFF channel axes for {path}: shape={shape}, axes={axes!r}; expected a 2D image with one channel/sample axis"
65 )
66 channels = extra[0][1] if extra else 1
67 return shape[axes.index("X")], shape[axes.index("Y")], channels
70_TURNED = {5, 6, 7, 8} # EXIF orientations that exchange width and height
73def _is_tiff(path: str | Path) -> bool:
74 return Path(path).suffix.lower() in {".tif", ".tiff"}
77def _displayed_size(image: ImagePil.Image) -> tuple[int, int]:
78 """Size after applying the EXIF orientation tag, as viewers display it."""
79 width, height = image.size
80 if image.getexif().get(0x0112) in _TURNED:
81 return height, width
82 return width, height
85def open_oriented(path: str | Path) -> ImagePil.Image:
86 """Open an image with its EXIF orientation applied, so pixels match the display.
88 Browsers and image viewers honour the tag; Pillow does not. Every pixel read
89 in Collectra goes through here, so coordinates agree with what the user sees.
90 TIFFs are left alone: their tags describe scientific channel layouts.
91 """
92 with ImagePil.open(path) as image:
93 if _is_tiff(path):
94 return image.copy()
95 return ImageOps.exif_transpose(image)
98def bake_orientation(path: str | Path) -> None:
99 """Rewrite a raster file in place with its EXIF orientation applied to the pixels.
101 For temporary training copies read by libraries that ignore the tag. Files
102 that are untagged, upright or TIFF are left byte-for-byte untouched.
103 """
104 path = Path(path)
105 if _is_tiff(path):
106 return
107 with ImagePil.open(path) as image:
108 if image.getexif().get(0x0112, 1) == 1:
109 return
110 image_format = image.format
111 oriented = ImageOps.exif_transpose(image)
112 oriented.save(path, format=image_format)
115def image_channel_count(path: str | Path) -> int:
116 """Inspect image metadata for its channel count; never convert image pixels."""
117 if Path(path).suffix.lower() in {".tif", ".tiff"}:
118 return _tiff_dimensions(path)[2]
119 with ImagePil.open(path) as image:
120 if image.mode == "P":
121 return 4 if "transparency" in image.info else 3
122 return len(image.getbands())
125def convert_image_to_rgb(path: str | Path) -> None:
126 """Rewrite an image file in place as 3-channel RGB (no-op if it already is)."""
127 path = Path(path)
128 try:
129 with ImagePil.open(path) as image:
130 if image.mode == "RGB":
131 return
132 converted = image.convert("RGB")
133 except Exception as error:
134 raise ValueError(f"Cannot convert {path.name} to RGB: {error}") from error
135 converted.save(path)
138def image_size(path: str | Path) -> tuple[int, int]:
139 """Return ``(width, height)`` from image metadata; supports multi-channel TIFFs."""
140 if Path(path).suffix.lower() in {".tif", ".tiff"}:
141 return _tiff_dimensions(path)[:2]
142 with ImagePil.open(path) as image:
143 return _displayed_size(image)
146def read_tiff_channels(path: str | Path, maxworkers: int | None = None):
147 """Decode a TIFF into HWC order using the same axis rules as metadata inspection."""
148 from tifffile import TiffFile
150 width, height, channels = _tiff_dimensions(path)
151 with TiffFile(path) as tiff:
152 series = tiff.series[0]
153 axes = series.axes
154 if maxworkers is None:
155 pixels = series.asarray()
156 else:
157 try:
158 pixels = series.asarray(maxworkers=maxworkers)
159 except TypeError:
160 # Older tifffile versions may not expose maxworkers.
161 pixels = series.asarray()
162 spatial = [axes.index("Y"), axes.index("X")]
163 order = spatial + [index for index in range(pixels.ndim) if index not in spatial]
164 return pixels.transpose(order).reshape(height, width, channels)
167@lru_cache(maxsize=4096)
168def _image_metadata(
169 path: str, modified_ns: int, file_size: int
170) -> tuple[int, int, str | None]:
171 """Read image dimensions and format once per file version."""
172 if Path(path).suffix.lower() in {".tif", ".tiff"}:
173 width, height, _ = _tiff_dimensions(path)
174 return width, height, "TIFF"
175 with ImagePil.open(path) as image:
176 width, height = _displayed_size(image)
177 return width, height, image.format
180class ImageArtefactCommands(ArtefactCommands):
181 """Commands applying to image artefacts stored in a pipeline node."""
183 @command
184 def extract(
185 self,
186 *inputs: str,
187 output: Path = Path("extracted"),
188 ) -> None:
189 """Extract this artefact from Collectra result folders."""
190 output = output.expanduser().resolve()
191 output.mkdir(parents=True, exist_ok=True)
193 sources: list[tuple[str, dict[str, Artefact]]] = []
194 if self.node.items:
195 sources.append(("configured", self.node.items))
197 for input_path in inputs:
198 path = Path(input_path).expanduser().resolve()
199 loaded = ArtefactNode(self.node.name, types=set(self.node.types))
200 loaded.process(self.node.name, path)
201 sources.append((path.stem, loaded.items))
203 for source_name, items in sources:
204 destination = output / source_name if len(sources) > 1 else output
205 destination.mkdir(parents=True, exist_ok=True)
206 for item in items.values():
207 if isinstance(item, Image):
208 suffix = ".png" if isinstance(item, ImageSegmentation) else ".jpg"
209 item.extract(destination / f"{item.id}{suffix}")
212class Orientation(Enum):
213 """Enumeration for image orientation states."""
215 NORTH = 0
216 WEST = 1
217 SOUTH = 2
218 EAST = 3
220 def to_string(self) -> str:
221 match self.value:
222 case 0:
223 return "north"
224 case 1:
225 return "west"
226 case 2:
227 return "south"
228 case 3:
229 return "east"
231 def to_degree(self) -> int:
232 match self.value:
233 case 0:
234 return 0
235 case 1:
236 return -90
237 case 2:
238 return -180
239 case 3:
240 return -270
242 @staticmethod
243 def from_string(direction: str) -> "Orientation":
244 direction = direction.strip().lower()
245 match direction:
246 case "north":
247 return Orientation.NORTH
248 case "west":
249 return Orientation.WEST
250 case "south":
251 return Orientation.SOUTH
252 case "east":
253 return Orientation.EAST
254 case _:
255 raise ValueError(f"Invalid degree for orientation: {direction}")
258class Image(Artefact):
259 """Base class for handling image data and metadata in Collectra workflows.
261 Provides core functionality for loading, encoding, and managing image files
262 with support for various formats and metadata extraction. Serves as the
263 foundation for more specialized image processing classes.
265 Attributes:
266 path (str): File system path to the image file.
267 raw_width (int): Width of the image in pixels.
268 raw_height (int): Height of the image in pixels.
269 format (str | None): Image format (PNG, JPEG, etc.) or None if unknown.
270 """
272 data: str | Path | ImagePil.Image = "" # Path to the image file
273 raw_width: int = 0 # Displayed image width in pixels
274 raw_height: int = 0 # Displayed image height in pixels
275 ext: str | None = "" # Image format (e.g., PNG, JPEG)
276 orientation: Orientation = Orientation.NORTH # Image orientation
278 @field_validator("orientation", mode="before")
279 @classmethod
280 def _orientation_from_text(cls, value):
281 if isinstance(value, str):
282 return Orientation.from_string(value)
283 return value
285 @classmethod
286 def cli_commands(cls, node: ArtefactNode, ext: str) -> ImageArtefactCommands:
287 """Expose image operations for a named pipeline artefact node."""
288 return ImageArtefactCommands(node, ext)
290 def attributes_to_ignore(self):
291 attributes = super().attributes_to_ignore()
292 [attributes.add(attr) for attr in ["raw_width", "raw_height", "ext"]]
293 return attributes
295 def serialize(self) -> dict:
296 serialized = super().serialize()
297 serialized["orientation"] = (
298 self.orientation.to_string()
299 if isinstance(self.orientation, Orientation)
300 else self.orientation
301 )
302 return serialized
304 def save(self, path: Path | str = None):
305 path = Path(path)
306 path.parent.mkdir(exist_ok=True, parents=True)
308 # Simply copy to new dest
309 shutil.copy(self.get_path(), path)
311 @staticmethod
312 def file_extensions() -> set[str]:
313 return {".png", ".jpg", ".jpeg", ".bmp", ".gif", ".tif", ".tiff", ".webp"}
315 @property
316 def width(self) -> int | float:
317 return self.raw_width
319 @property
320 def height(self) -> int | float:
321 return self.raw_height
323 def model_post_init(self, __context: Any) -> None:
324 """Load an Image's metadata from its file path.
326 Loads image metadata (dimensions and format) from the specified file
327 and returns a configured Image instance.
329 Args:
330 data (Path): Path to the image file to load.
332 Returns:
333 Image: Configured Image instance with loaded metadata.
335 Raises:
336 FileNotFoundError: If the image file doesn't exist.
337 PIL.UnidentifiedImageError: If the file is not a valid image.
338 """
339 super().model_post_init(__context)
340 if not self.data:
341 raise ValueError("Image data path is empty.")
342 if not isinstance(self.data, (str, Path)):
343 raise TypeError("Image data must be a file path.")
344 if not isinstance(self.data, Path):
345 self.data = Path.cwd() / self.data
346 if not self.data.exists() or not self.data.is_file():
347 raise FileNotFoundError(f"Image file not found: {self.data}")
348 stat = self.data.stat()
349 self.raw_width, self.raw_height, self.ext = _image_metadata(
350 str(self.data.resolve()), stat.st_mtime_ns, stat.st_size
351 )
353 def __call__(self) -> str:
354 return str(self.get_path())
356 def get_path(self) -> Path:
357 """Get the file path of the image.
359 Returns:
360 Path: The file path of the image.
361 """
362 if not isinstance(self.data, Path):
363 if not isinstance(self.data, Image):
364 raise Exception(
365 "This appear to be not an Image object. Artefact path is only available for Image object."
366 )
367 raise Exception("Image data is not a valid Path object.")
368 return self.data
370 @staticmethod
371 def is_image_file(path: Path) -> bool:
372 """Check if a file path represents a supported image format.
374 Args:
375 path (Path): File path to check.
377 Returns:
378 bool: True if the file extension indicates a supported image format.
379 """
380 return path.suffix.lower() in Image.file_extensions()
382 # The formats language-model APIs accept. An image in any other format,
383 # such as a TIFF scan, is sent as a high-quality JPEG, which keeps crops of
384 # big scans under the APIs' size limits, or as PNG if JPEG cannot hold its
385 # pixels (transparency, 16-bit).
386 ENCODED_FORMATS: ClassVar[frozenset[str]] = frozenset(
387 {"JPEG", "PNG", "GIF", "WEBP"}
388 )
389 JPEG_MODES: ClassVar[frozenset[str]] = frozenset({"RGB", "L", "CMYK"})
390 CONVERTED_JPEG_QUALITY: ClassVar[int] = 95
392 def _encoded_format(self) -> str:
393 fmt = (self.ext or "").upper()
394 if fmt in self.ENCODED_FORMATS:
395 return fmt
396 with ImagePil.open(self.get_path()) as image: # reads only the header
397 return "JPEG" if image.mode in self.JPEG_MODES else "PNG"
399 def _load_buffer(self, img: ImagePil.Image) -> bytes:
400 fmt = self._encoded_format()
401 options = {}
402 if fmt == "JPEG" and (self.ext or "").upper() != "JPEG":
403 options["quality"] = self.CONVERTED_JPEG_QUALITY
404 buffer = io.BytesIO()
405 img.save(buffer, format=fmt, **options)
406 buffer.seek(0)
407 return buffer.read()
409 def load(self) -> bytes:
410 """Load the image file content as raw bytes.
412 Returns:
413 bytes: Raw binary content of the image file.
415 Raises:
416 FileNotFoundError: If the image file doesn't exist.
417 PermissionError: If the file cannot be read due to permissions.
418 """
419 img = self.pil()
420 return self._load_buffer(img)
422 def get_encoding(self) -> str:
423 """Get the base64 encoded representation of the image.
425 Loads the image content and encodes it as a base64 string,
426 suitable for embedding in JSON or other text-based formats.
428 Returns:
429 str: Base64 encoded string representation of the image.
430 """
431 return base64.b64encode(self.load()).decode("utf-8")
433 def mime(self) -> str:
434 """The MIME type of ``load()``: the image's own format if language
435 models accept it (JPEG, PNG, GIF or WebP), otherwise JPEG or PNG."""
436 return f"image/{self._encoded_format().lower()}"
438 def pil(self) -> ImagePil.Image:
439 image = open_oriented(self.get_path())
440 return image.rotate(self.orientation.to_degree(), expand=True)
442 def display(self, context) -> dict:
443 return context.image(self)
445 def display_bounds(self):
446 """Region in source pixels represented by this image's viewer."""
447 return (0, 0, self.raw_width, self.raw_height)
449 def _extract(self, path: Path) -> None:
450 """Extract the image to a specified path."""
451 if path.suffix == "":
452 path = path.with_suffix(".jpg")
453 self.pil().save(path)
455 def check_valid_relative_crop_values(
456 self,
457 x_center: float,
458 y_center: float,
459 width_relative: float,
460 height_relative: float,
461 ):
462 if not (0.0 <= x_center <= 1.0):
463 raise ValueError(f"x_center is {x_center}")
465 if not (0.0 <= y_center <= 1.0):
466 raise ValueError(f"y_center is {y_center}")
468 if not (0.0 <= width_relative <= 1.0):
469 raise ValueError(f"width_relative is {width_relative}")
471 if not (0.0 <= height_relative <= 1.0):
472 raise ValueError(f"height_relative is {height_relative}")
474 def make_crop(
475 self,
476 x_center: float,
477 y_center: float,
478 width_relative: float,
479 height_relative: float,
480 confidence: float | None = None,
481 orientation: Orientation = Orientation.NORTH,
482 name: str = "",
483 ) -> "ImageCrop":
485 self.check_valid_relative_crop_values(
486 x_center,
487 y_center,
488 width_relative,
489 height_relative,
490 )
492 return ImageCrop(
493 name=name if name else self.name,
494 data=self.data,
495 x_center=x_center,
496 y_center=y_center,
497 width_relative=width_relative,
498 height_relative=height_relative,
499 confidence=confidence,
500 orientation=orientation,
501 )
503 def make_crop_bounding_box(
504 self,
505 left,
506 top,
507 right,
508 bottom,
509 min_height: float = 0.0,
510 confidence: float | None = None,
511 ) -> "ImageCrop":
512 bbox_width = right - left
513 bbox_height = bottom - top
514 x_center = (left + 0.5 * bbox_width) / self.width
515 y_center = (top + 0.5 * bbox_height) / self.height
516 width_relative = bbox_width / self.width
517 height_relative = bbox_height / self.height
519 return self.make_crop(
520 x_center=x_center,
521 y_center=y_center,
522 width_relative=width_relative,
523 height_relative=height_relative,
524 confidence=confidence,
525 )
527 def evaluate(self, gold: "ImageCrop") -> float:
528 raise NotImplementedError(
529 "Base Image class does not implement evaluate(). Use ImageCrop instead."
530 )
532 def set_rel_to_src_parent(self) -> None:
533 pass
536class ImageCrop(Image):
537 """Specialized image class for handling cropped regions of images.
539 Extends the base Image class to support coordinate-based cropping with
540 relative positioning. Coordinates are specified as normalized values
541 (0.0 to 1.0) relative to the original image dimensions.
543 Attributes:
544 x_center (float): Normalized x-coordinate of crop center (0.0 to 1.0).
545 y_center (float): Normalized y-coordinate of crop center (0.0 to 1.0).
546 width_relative (float): Normalized width of crop region (0.0 to 1.0).
547 height_relative (float): Normalized height of crop region (0.0 to 1.0).
548 """
550 x_center: float = 0.5
551 y_center: float = 0.5
552 width_relative: float = 1.0
553 height_relative: float = 1.0
554 confidence: float | None = None
555 source_parent: Any = Field(default=None, repr=False) # Image | ImageCrop | None
557 def attributes_to_ignore(self):
558 return super().attributes_to_ignore() | {"source_parent"}
560 def display_bounds(self):
561 return self.coordinates()
563 def save(self, path: Path | str = None):
564 im = self.source_parent.pil() if self.source_parent else self.pil()
565 if path is None:
566 raise ValueError("Path must be provided to save the cropped image.")
567 im.save(path)
569 @property
570 def width(self):
571 return self.width_relative * self.raw_width
573 @property
574 def height(self):
575 return self.height_relative * self.raw_height
577 def add_source_parent(self, parent: "Image | ImageCrop") -> None:
578 self.source_parent = parent
580 def set_rel_to_src_parent(self) -> None:
582 if not self.source_parent:
583 return
585 if type(self.source_parent) == ImageCrop:
586 self.source_parent.set_rel_to_src_parent()
587 dx = self.x_center - self.source_parent.x_center
588 dy = self.y_center - self.source_parent.y_center
589 self.x_center = 0.5 + dx / self.source_parent.width_relative
590 self.y_center = 0.5 + dy / self.source_parent.height_relative
591 self.width_relative /= self.source_parent.width_relative
592 self.height_relative /= self.source_parent.height_relative
594 match self.source_parent.orientation.to_degree():
595 case -90:
596 self.x_center, self.y_center = 1 - self.y_center, self.x_center
597 self.width_relative, self.height_relative = (
598 self.height_relative,
599 self.width_relative,
600 )
601 case -180:
602 self.x_center, self.y_center = 1 - self.x_center, 1 - self.y_center
603 case -270:
604 self.x_center, self.y_center = self.y_center, 1 - self.x_center
605 self.width_relative, self.height_relative = (
606 self.height_relative,
607 self.width_relative,
608 )
610 def pil(self) -> ImagePil.Image:
611 coordinates = self.coordinates()
612 left, upper, right, bottom = coordinates
613 if right <= left or bottom <= upper:
614 raise ValueError(
615 f"ImageCrop {self.id!r} produces an empty pixel crop: "
616 f"input_file={str(self.source_file) if self.source_file else 'unknown'!r}, "
617 f"image_file={str(self.get_path())!r}, raw_size=({self.raw_width}, "
618 f"{self.raw_height}), normalized=(x_center={self.x_center}, "
619 f"y_center={self.y_center}, width={self.width_relative}, "
620 f"height={self.height_relative}), pixel_box={coordinates}"
621 )
622 im_crop = open_oriented(self.get_path()).crop(coordinates)
623 return im_crop.rotate(self.orientation.to_degree(), expand=True)
625 def coordinates(self) -> tuple[float, float, float, float]:
626 """Calculate absolute pixel coordinates for the crop region.
628 Converts the normalized crop coordinates to absolute pixel coordinates
629 within the bounds of the original image dimensions.
631 Returns:
632 tuple[float, float, float, float]: Absolute coordinates as
633 (left, upper, right, bottom) in pixels.
634 """
635 x_center = self.x_center * self.raw_width
636 y_center = self.y_center * self.raw_height
637 actual_width_half = self.raw_width * self.width_relative / 2
638 actual_height_half = self.raw_height * self.height_relative / 2
639 left = max(0, min(int(x_center - actual_width_half), self.raw_width))
640 upper = max(0, min(int(y_center - actual_height_half), self.raw_height))
641 right = max(0, min(int(x_center + actual_width_half), self.raw_width))
642 bottom = max(0, min(int(y_center + actual_height_half), self.raw_height))
644 return (left, upper, right, bottom)
646 def make_crop(
647 self,
648 x_center: float,
649 y_center: float,
650 width_relative: float,
651 height_relative: float,
652 confidence: float | None = None,
653 orientation: Orientation = Orientation.NORTH,
654 name: str = "",
655 ) -> "ImageCrop":
657 degree_transformed = orientation.to_degree()
659 if degree_transformed == -90:
660 x_center, y_center = y_center, 1 - x_center
661 width_relative, height_relative = height_relative, width_relative
662 elif degree_transformed == -180:
663 x_center, y_center = 1 - x_center, 1 - y_center
664 elif degree_transformed == -270:
665 x_center, y_center = 1 - y_center, x_center
666 width_relative, height_relative = height_relative, width_relative
668 name = name if name else self.name
670 return super().make_crop(
671 x_center=self.x_center + (x_center - 0.5) * self.width_relative,
672 y_center=self.y_center + (y_center - 0.5) * self.height_relative,
673 width_relative=width_relative * self.width_relative,
674 height_relative=height_relative * self.height_relative,
675 confidence=confidence,
676 orientation=orientation,
677 name=name,
678 )
680 @staticmethod
681 def compute_iou(boxA, boxB):
682 # determine the (x, y)-coordinates of the intersection rectangle
683 xA = max(boxA[0], boxB[0])
684 yA = max(boxA[1], boxB[1])
685 xB = min(boxA[2], boxB[2])
686 yB = min(boxA[3], boxB[3])
688 # compute the area of intersection rectangle
689 interWidth = max(0, xB - xA)
690 interHeight = max(0, yB - yA)
691 interArea = interWidth * interHeight
693 # compute the area of both the prediction and ground-truth rectangles
694 boxAArea = (boxA[2] - boxA[0]) * (boxA[3] - boxA[1])
695 boxBArea = (boxB[2] - boxB[0]) * (boxB[3] - boxB[1])
697 # compute the intersection over union by taking the intersection
698 # area and dividing it by the sum of prediction + ground-truth
699 # areas - the interesection area
700 if boxAArea + boxBArea - interArea == 0:
701 return 0.0
702 iou = interArea / float(boxAArea + boxBArea - interArea)
704 # return the intersection over union value
705 return iou
707 def evaluate(self, gold: "ImageCrop") -> float:
708 if not isinstance(gold, ImageCrop):
709 raise ValueError("Reference data must be an instance of ImageCrop.")
710 iou = 0.0
711 boxA = self.coordinates()
712 boxB = gold.coordinates()
713 iou = self.compute_iou(boxA, boxB)
714 return iou
717class ImageSegmentation(Image):
718 """An image region defined by a source-sized binary PNG mask.
720 Mask pixels are 0 outside the region and 1 inside. Masks in Pillow's
721 one-bit mode are also supported. The rendered image is cropped to the
722 nonzero bounding box and retains source alpha within the region.
723 """
725 mask: str | Path = ""
726 _mask_path: Path | None = PrivateAttr(default=None)
728 def model_post_init(self, __context: Any) -> None:
729 super().model_post_init(__context)
730 if not self.mask:
731 raise ValueError("ImageSegmentation mask path is empty")
732 self.mask = Path(self.mask)
733 self._mask_path = self.mask.resolve()
734 self._mask_image()
736 def attributes_to_ignore(self):
737 return super().attributes_to_ignore() | {"_mask_path"}
739 def _mask_image(self) -> ImagePil.Image:
740 import numpy as np
742 with ImagePil.open(self._mask_path) as mask:
743 if mask.format != "PNG":
744 raise ValueError("ImageSegmentation mask must be a PNG file")
745 if mask.size != (self.raw_width, self.raw_height):
746 raise ValueError("Mask dimensions must match the source image")
747 if mask.mode in {"L", "P"}:
748 # A histogram validates binary values without large temporary
749 # NumPy arrays for every full-resolution mask in the viewer.
750 if any(mask.histogram()[2:]):
751 raise ValueError(
752 "Mask must contain only single-channel 0 and 1 pixels"
753 )
754 alpha = mask.point([0, 255] + [0] * 254, mode="L")
755 elif mask.mode == "1":
756 alpha = mask.convert("L")
757 else:
758 pixels = np.asarray(mask)
759 if pixels.ndim != 2 or not np.isin(pixels, [0, 1]).all():
760 raise ValueError(
761 "Mask must contain only single-channel 0 and 1 pixels"
762 )
763 alpha = ImagePil.fromarray(pixels.astype("uint8") * 255)
764 if alpha.getbbox() is None:
765 raise ValueError("ImageSegmentation mask is empty")
766 return alpha
768 def serialize(self) -> dict:
769 serialized = super().serialize()
770 # Results are serialized from inside their results folder (the working
771 # directory), and loaded from it, so masks there are stored relative
772 # to it and the folder stays portable. Masks elsewhere keep their path.
773 mask = Path(self.mask)
774 if mask.is_absolute():
775 try:
776 mask = self._mask_path.relative_to(Path.cwd().resolve())
777 except ValueError:
778 pass
779 serialized["mask"] = mask.as_posix()
780 return serialized
782 def display_bounds(self):
783 return self._mask_image().getbbox()
785 @property
786 def width(self):
787 left, top, right, bottom = self.display_bounds()
788 return right - left
790 @property
791 def height(self):
792 left, top, right, bottom = self.display_bounds()
793 return bottom - top
795 def masked_pil(self, image: ImagePil.Image) -> ImagePil.Image:
796 """Mask and crop an unrotated source image or display projection."""
797 from PIL import ImageChops
799 mask = self._mask_image()
800 if image.size != mask.size:
801 raise ValueError("Mask dimensions must match the source image")
802 result = image.convert("RGBA")
803 result.putalpha(ImageChops.multiply(result.getchannel("A"), mask))
804 return result.crop(mask.getbbox()).rotate(
805 self.orientation.to_degree(), expand=True
806 )
808 def pil(self) -> ImagePil.Image:
809 return self.masked_pil(open_oriented(self.get_path()))
811 def _load_buffer(self, img: ImagePil.Image) -> bytes:
812 buffer = io.BytesIO()
813 img.save(buffer, format="PNG")
814 return buffer.getvalue()
816 def mime(self) -> str:
817 return "image/png"
819 def save(self, path: Path | str = None):
820 if path is None:
821 raise ValueError("Path must be provided to save the segmented image")
822 self.extract(path)
824 def _extract(self, path: Path) -> None:
825 if not path.suffix:
826 path = path.with_suffix(".png")
827 self.pil().save(path)