Coverage for collectra/displays/images.py: 91.47%
129 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 previews, crop coordinates and child image annotations."""
3from collections import OrderedDict
4from collectra.utils import load_class_from_string
5from .image_segmentation import display_bounds
6from .preview import bounded, open_preview
8# Share the few most recent encodings across contexts and panels.
9_PREVIEW_CACHE_SIZE = 6
10_preview_cache = OrderedDict()
13def region(context, image, region, inverse=False):
14 """Transform source-normalized boxes to/from the rotated crop viewer."""
15 left, top, right, bottom = display_bounds(image)
16 width, height = right - left, bottom - top
17 if width <= 0 or height <= 0:
18 raise ValueError("Cannot display an empty image crop")
19 x, y = region["x_center"], region["y_center"]
20 w, h = region["width_relative"], region["height_relative"]
21 turns = (image.orientation.to_degree() // 90) % 4
22 if inverse:
23 for _ in range((-turns) % 4):
24 x, y, w, h = y, 1 - x, h, w
25 x, y = (left + x * width) / image.raw_width, (
26 top + y * height
27 ) / image.raw_height
28 w, h = w * width / image.raw_width, h * height / image.raw_height
29 else:
30 x, y = (x * image.raw_width - left) / width, (
31 y * image.raw_height - top
32 ) / height
33 w, h = w * image.raw_width / width, h * image.raw_height / height
34 for _ in range(turns):
35 x, y, w, h = y, 1 - x, h, w
36 return dict(x_center=x, y_center=y, width_relative=w, height_relative=h)
39def annotations(context, image):
40 from collectra.types.images import ImageCrop, ImageSegmentation
42 rows = []
43 for node_id, record in context.records.items():
44 parents = record.get("parents", [])
45 parents = [parents] if isinstance(parents, str) else parents
46 if image.id not in parents:
47 continue
48 try:
49 if not issubclass(
50 load_class_from_string(record["type"]),
51 (ImageCrop, ImageSegmentation),
52 ):
53 continue
54 except (ImportError, AttributeError):
55 continue
56 child = context.artefact(node_id)
57 if (
58 not isinstance(child, (ImageCrop, ImageSegmentation))
59 or child.get_path().resolve() != image.get_path().resolve()
60 ):
61 continue
62 if isinstance(child, ImageSegmentation):
63 from PIL import Image as PILImage, ImageChops
65 alpha = child._mask_image()
66 if isinstance(image, ImageSegmentation):
67 alpha = ImageChops.multiply(alpha, image._mask_image())
68 alpha = alpha.crop(display_bounds(image)).rotate(
69 image.orientation.to_degree(), expand=True
70 )
71 bounds = alpha.getbbox()
72 if bounds is None:
73 continue
74 left, top, right, bottom = bounds
75 cropped = bounded(alpha.crop(bounds), mask=True, max_pixels=context.max_pixels)
76 overlay = PILImage.new("RGBA", cropped.size, "white")
77 overlay.putalpha(cropped)
78 rows.append(
79 {
80 "id": node_id,
81 "type": record["type"],
82 "label": record.get("label", ""),
83 "name": record.get("name", ""),
84 "mask_source": context.publish_image(overlay),
85 "mask_region": {
86 "x": left / alpha.width,
87 "y": top / alpha.height,
88 "width": (right - left) / alpha.width,
89 "height": (bottom - top) / alpha.height,
90 },
91 }
92 )
93 continue
94 region = {
95 key: getattr(child, key)
96 for key in ("x_center", "y_center", "width_relative", "height_relative")
97 }
98 rows.append(
99 {
100 "id": node_id,
101 "type": record["type"],
102 "label": record.get("label", ""),
103 "name": record.get("name", ""),
104 "confidence": child.confidence,
105 "crop_region": context.region(image, region),
106 }
107 )
108 return rows
111def image(context, item):
112 from PIL import Image as PILImage
114 from collectra.types.images import (
115 ImageSegmentation,
116 image_channel_count,
117 read_tiff_channels,
118 )
120 path = item.get_path()
121 view_count = 1
122 key = _preview_key(context, item, path)
123 if key in _preview_cache:
124 _preview_cache.move_to_end(key)
125 source, view_count = _preview_cache[key]
126 return _image_view(context, item, path, source, view_count)
127 if path.suffix.lower() in {".tif", ".tiff"}:
128 import numpy as np
129 from tifffile import TiffFile
131 channels = image_channel_count(path)
132 # Only complete RGB triplets form multiple views. Other spectral
133 # layouts keep the first-triplet/gray preview and can override display.
134 if channels >= 3 and channels % 3 == 0:
135 view_count = channels // 3
136 if context.rgb_view >= view_count:
137 raise ValueError(f"RGB view index must be less than {view_count}")
138 start = context.rgb_view * 3
139 stop = start + (3 if channels >= 3 else 1)
140 with TiffFile(path) as tiff:
141 series = tiff.series[0]
142 # CYX/QYX stacks store each channel on a separate page. Decode
143 # just this view instead of all 75 channels on every button click.
144 pages = series.pages
145 if len(pages) == channels and all(
146 pages[i].axes == "YX" for i in range(start, stop)
147 ):
148 pixels = np.stack(
149 [pages[i].asarray() for i in range(start, stop)], axis=-1
150 )
151 else:
152 pixels = read_tiff_channels(path)[..., start:stop]
153 if pixels.shape[2] == 1:
154 pixels = pixels[..., 0]
155 if pixels.dtype != np.uint8:
156 pixels = pixels.astype(float)
157 low, high = np.nanmin(pixels), np.nanmax(pixels)
158 pixels = np.nan_to_num((pixels - low) / (high - low or 1) * 255).astype(
159 np.uint8
160 )
161 preview = PILImage.fromarray(pixels)
162 else:
163 if context.rgb_view:
164 raise ValueError("This image has only one RGB view")
165 preview = open_preview(path, display_bounds(item), "RGBA" if isinstance(item, ImageSegmentation) else "RGB", max_pixels=context.max_pixels)
166 if path.suffix.lower() in {".tif", ".tiff"}:
167 preview = bounded(preview.crop(display_bounds(item)), max_pixels=context.max_pixels)
168 preview = preview.rotate(
169 item.orientation.to_degree(), expand=True
170 )
171 source = context.publish_image(preview)
172 if key is not None:
173 _preview_cache[key] = (source, view_count)
174 while len(_preview_cache) > _PREVIEW_CACHE_SIZE:
175 _preview_cache.popitem(last=False)
176 return _image_view(context, item, path, source, view_count)
179def _preview_key(context, item, path):
180 """What the encoded preview depends on, or None when it is not cached
181 (segmentations also depend on their mask file)."""
182 from collectra.types.images import ImageSegmentation
184 if isinstance(item, ImageSegmentation):
185 return None
186 try:
187 stat = path.stat()
188 return (
189 str(path.resolve()),
190 stat.st_mtime_ns,
191 stat.st_size,
192 context.rgb_view,
193 context.max_pixels,
194 tuple(item.display_bounds()),
195 item.orientation.to_degree(),
196 )
197 except OSError:
198 return None
201def links(context, item):
202 """The Link children of ``item``: each one's id and name (its label)."""
203 from collectra.types.links import is_link_type
205 found = []
206 for node_id, record in context.records.items():
207 parents = record.get("parents") or []
208 if isinstance(parents, str):
209 parents = [parents]
210 if is_link_type(record.get("type", "")) and item.id in parents:
211 found.append({"id": node_id, "name": record.get("label", node_id)})
212 return found
215def _image_view(context, item, path, source, view_count):
216 from collectra.types.images import ImageSegmentation
217 from .image_segmentation import segmentation
219 view = {
220 "kind": "image",
221 "source": source,
222 "image_path": str(path),
223 "target_id": item.id,
224 "annotations": context.annotations(item),
225 "can_create_crop": True,
226 "can_rotate": True,
227 "links": context.links(item),
228 "rgb_view_index": context.rgb_view,
229 "rgb_view_count": view_count,
230 }
231 if isinstance(item, ImageSegmentation):
232 view["segmentation"] = segmentation(context, item)
233 return view