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

1"""Image handling and processing classes for the Collectra system. 

2 

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. 

7 

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 

13 

14Classes: 

15 Image: Base class for image handling and metadata 

16 ImageCrop: Specialized class for cropped image regions 

17""" 

18 

19__all__ = ["Image", "ImageCrop", "ImageSegmentation"] 

20 

21 

22import base64 

23import io 

24import shutil 

25from enum import Enum 

26from functools import lru_cache 

27from pathlib import Path 

28from typing import Any, ClassVar 

29 

30from PIL import Image as ImagePil 

31from PIL import ImageOps 

32from pydantic import Field, PrivateAttr, field_validator 

33 

34from collectra.cli import command 

35 

36from .base import Artefact, ArtefactCommands, ArtefactNode 

37 

38 

39def _tiff_dimensions(path: str | Path) -> tuple[int, int, int]: 

40 """Return width, height, channels from TIFF headers, without decoding pixels. 

41 

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 

47 

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 

68 

69 

70_TURNED = {5, 6, 7, 8} # EXIF orientations that exchange width and height 

71 

72 

73def _is_tiff(path: str | Path) -> bool: 

74 return Path(path).suffix.lower() in {".tif", ".tiff"} 

75 

76 

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 

83 

84 

85def open_oriented(path: str | Path) -> ImagePil.Image: 

86 """Open an image with its EXIF orientation applied, so pixels match the display. 

87 

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) 

96 

97 

98def bake_orientation(path: str | Path) -> None: 

99 """Rewrite a raster file in place with its EXIF orientation applied to the pixels. 

100 

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) 

113 

114 

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()) 

123 

124 

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) 

136 

137 

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) 

144 

145 

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 

149 

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) 

165 

166 

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 

178 

179 

180class ImageArtefactCommands(ArtefactCommands): 

181 """Commands applying to image artefacts stored in a pipeline node.""" 

182 

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) 

192 

193 sources: list[tuple[str, dict[str, Artefact]]] = [] 

194 if self.node.items: 

195 sources.append(("configured", self.node.items)) 

196 

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)) 

202 

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}") 

210 

211 

212class Orientation(Enum): 

213 """Enumeration for image orientation states.""" 

214 

215 NORTH = 0 

216 WEST = 1 

217 SOUTH = 2 

218 EAST = 3 

219 

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" 

230 

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 

241 

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}") 

256 

257 

258class Image(Artefact): 

259 """Base class for handling image data and metadata in Collectra workflows. 

260 

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. 

264 

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 """ 

271 

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 

277 

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 

284 

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) 

289 

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 

294 

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 

303 

304 def save(self, path: Path | str = None): 

305 path = Path(path) 

306 path.parent.mkdir(exist_ok=True, parents=True) 

307 

308 # Simply copy to new dest 

309 shutil.copy(self.get_path(), path) 

310 

311 @staticmethod 

312 def file_extensions() -> set[str]: 

313 return {".png", ".jpg", ".jpeg", ".bmp", ".gif", ".tif", ".tiff", ".webp"} 

314 

315 @property 

316 def width(self) -> int | float: 

317 return self.raw_width 

318 

319 @property 

320 def height(self) -> int | float: 

321 return self.raw_height 

322 

323 def model_post_init(self, __context: Any) -> None: 

324 """Load an Image's metadata from its file path. 

325 

326 Loads image metadata (dimensions and format) from the specified file 

327 and returns a configured Image instance. 

328 

329 Args: 

330 data (Path): Path to the image file to load. 

331 

332 Returns: 

333 Image: Configured Image instance with loaded metadata. 

334 

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 ) 

352 

353 def __call__(self) -> str: 

354 return str(self.get_path()) 

355 

356 def get_path(self) -> Path: 

357 """Get the file path of the image. 

358 

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 

369 

370 @staticmethod 

371 def is_image_file(path: Path) -> bool: 

372 """Check if a file path represents a supported image format. 

373 

374 Args: 

375 path (Path): File path to check. 

376 

377 Returns: 

378 bool: True if the file extension indicates a supported image format. 

379 """ 

380 return path.suffix.lower() in Image.file_extensions() 

381 

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 

391 

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" 

398 

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() 

408 

409 def load(self) -> bytes: 

410 """Load the image file content as raw bytes. 

411 

412 Returns: 

413 bytes: Raw binary content of the image file. 

414 

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) 

421 

422 def get_encoding(self) -> str: 

423 """Get the base64 encoded representation of the image. 

424 

425 Loads the image content and encodes it as a base64 string, 

426 suitable for embedding in JSON or other text-based formats. 

427 

428 Returns: 

429 str: Base64 encoded string representation of the image. 

430 """ 

431 return base64.b64encode(self.load()).decode("utf-8") 

432 

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()}" 

437 

438 def pil(self) -> ImagePil.Image: 

439 image = open_oriented(self.get_path()) 

440 return image.rotate(self.orientation.to_degree(), expand=True) 

441 

442 def display(self, context) -> dict: 

443 return context.image(self) 

444 

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) 

448 

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) 

454 

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}") 

464 

465 if not (0.0 <= y_center <= 1.0): 

466 raise ValueError(f"y_center is {y_center}") 

467 

468 if not (0.0 <= width_relative <= 1.0): 

469 raise ValueError(f"width_relative is {width_relative}") 

470 

471 if not (0.0 <= height_relative <= 1.0): 

472 raise ValueError(f"height_relative is {height_relative}") 

473 

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": 

484 

485 self.check_valid_relative_crop_values( 

486 x_center, 

487 y_center, 

488 width_relative, 

489 height_relative, 

490 ) 

491 

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 ) 

502 

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 

518 

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 ) 

526 

527 def evaluate(self, gold: "ImageCrop") -> float: 

528 raise NotImplementedError( 

529 "Base Image class does not implement evaluate(). Use ImageCrop instead." 

530 ) 

531 

532 def set_rel_to_src_parent(self) -> None: 

533 pass 

534 

535 

536class ImageCrop(Image): 

537 """Specialized image class for handling cropped regions of images. 

538 

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. 

542 

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 """ 

549 

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 

556 

557 def attributes_to_ignore(self): 

558 return super().attributes_to_ignore() | {"source_parent"} 

559 

560 def display_bounds(self): 

561 return self.coordinates() 

562 

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) 

568 

569 @property 

570 def width(self): 

571 return self.width_relative * self.raw_width 

572 

573 @property 

574 def height(self): 

575 return self.height_relative * self.raw_height 

576 

577 def add_source_parent(self, parent: "Image | ImageCrop") -> None: 

578 self.source_parent = parent 

579 

580 def set_rel_to_src_parent(self) -> None: 

581 

582 if not self.source_parent: 

583 return 

584 

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 

593 

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 ) 

609 

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) 

624 

625 def coordinates(self) -> tuple[float, float, float, float]: 

626 """Calculate absolute pixel coordinates for the crop region. 

627 

628 Converts the normalized crop coordinates to absolute pixel coordinates 

629 within the bounds of the original image dimensions. 

630 

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)) 

643 

644 return (left, upper, right, bottom) 

645 

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": 

656 

657 degree_transformed = orientation.to_degree() 

658 

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 

667 

668 name = name if name else self.name 

669 

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 ) 

679 

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]) 

687 

688 # compute the area of intersection rectangle 

689 interWidth = max(0, xB - xA) 

690 interHeight = max(0, yB - yA) 

691 interArea = interWidth * interHeight 

692 

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]) 

696 

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) 

703 

704 # return the intersection over union value 

705 return iou 

706 

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 

715 

716 

717class ImageSegmentation(Image): 

718 """An image region defined by a source-sized binary PNG mask. 

719 

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 """ 

724 

725 mask: str | Path = "" 

726 _mask_path: Path | None = PrivateAttr(default=None) 

727 

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() 

735 

736 def attributes_to_ignore(self): 

737 return super().attributes_to_ignore() | {"_mask_path"} 

738 

739 def _mask_image(self) -> ImagePil.Image: 

740 import numpy as np 

741 

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 

767 

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 

781 

782 def display_bounds(self): 

783 return self._mask_image().getbbox() 

784 

785 @property 

786 def width(self): 

787 left, top, right, bottom = self.display_bounds() 

788 return right - left 

789 

790 @property 

791 def height(self): 

792 left, top, right, bottom = self.display_bounds() 

793 return bottom - top 

794 

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 

798 

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 ) 

807 

808 def pil(self) -> ImagePil.Image: 

809 return self.masked_pil(open_oriented(self.get_path())) 

810 

811 def _load_buffer(self, img: ImagePil.Image) -> bytes: 

812 buffer = io.BytesIO() 

813 img.save(buffer, format="PNG") 

814 return buffer.getvalue() 

815 

816 def mime(self) -> str: 

817 return "image/png" 

818 

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) 

823 

824 def _extract(self, path: Path) -> None: 

825 if not path.suffix: 

826 path = path.with_suffix(".png") 

827 self.pil().save(path)