File: detection.py

package info (click to toggle)
python-sigima 1.1.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 25,608 kB
  • sloc: python: 35,251; makefile: 3
file content (628 lines) | stat: -rw-r--r-- 19,175 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
# Copyright (c) DataLab Platform Developers, BSD 3-Clause license, see LICENSE file.

"""
Detection computation module
----------------------------

This module provides algorithms for detecting objects or patterns in images,
such as blobs, peaks, or custom structures.

Main features include:

- Blob and peak detection algorithms
- Support for object localization and counting

Detection algorithms are fundamental for many image analysis pipelines,
enabling automated extraction of regions or features of interest.
"""

# pylint: disable=invalid-name  # Allows short reference names like x, y, ...

# Note:
# ----
# All dataset classes must also be imported in the sigima.params module.

from __future__ import annotations

import guidata.dataset as gds

import sigima.enums
import sigima.tools.image
from sigima.config import _
from sigima.objects import (
    GeometryResult,
    ImageObj,
    KindShape,
    create_image_roi_around_points,
)
from sigima.proc.decorator import computation_function
from sigima.proc.image.base import compute_geometry_from_obj

# NOTE: Only parameter classes DEFINED in this module should be included in __all__.
# Parameter classes imported from other modules (like sigima.proc.base) should NOT
# be re-exported to avoid Sphinx cross-reference conflicts. The sigima.params module
# serves as the central API point that imports and re-exports all parameter classes.
__all__ = [
    "BaseBlobParam",
    "BlobDOGParam",
    "BlobDOHParam",
    "BlobLOGParam",
    "BlobOpenCVParam",
    "ContourShapeParam",
    "DetectionROIParam",
    "GenericDetectionParam",
    "HoughCircleParam",
    "Peak2DDetectionParam",
    "apply_detection_rois",
    "blob_dog",
    "blob_doh",
    "blob_log",
    "blob_opencv",
    "contour_shape",
    "hough_circle_peaks",
    "peak_detection",
    "store_roi_creation_metadata",
]


class DetectionROIParam(gds.DataSet):
    """ROI creation parameters for detection algorithms.

    This class can be inherited by any detection parameter class to provide
    standardized ROI creation functionality.
    """

    _roi_g = gds.BeginGroup(_("Regions of interest"))
    _prop_create_rois = gds.ValueProp(False)
    create_rois = gds.BoolItem(
        _("Create regions of interest"),
        default=False,
        help=_(
            "Regions of interest will be created around detected features, "
            "if at least two features are detected.\n"
            "ROI size is optimized based on feature spacing."
        ),
    ).set_prop("display", store=_prop_create_rois)
    roi_geometry = gds.ChoiceItem(
        _("ROI geometry"),
        sigima.enums.DetectionROIGeometry,
        default=sigima.enums.DetectionROIGeometry.RECTANGLE,
    ).set_prop("display", active=_prop_create_rois)
    _roi_g_e = gds.EndGroup(_("Regions of interest"))


def store_roi_creation_metadata(
    geometry: GeometryResult | None,
    create_rois: bool,
    roi_geometry: sigima.enums.DetectionROIGeometry | None = None,
) -> GeometryResult | None:
    """Store ROI creation metadata in geometry result attributes.

    This function is called by computation functions to mark that ROI creation
    should be performed on the result. The actual ROI creation is done later
    via apply_detection_rois().

    Args:
        geometry: Geometry result from detection
        create_rois: Whether to create ROIs
        roi_geometry: ROI geometry type (if None, uses default RECTANGLE)

    Returns:
        The same geometry object (for chaining), or None if geometry is None

    Example:
        >>> geometry = compute_geometry_from_obj(...)
        >>> return store_roi_creation_metadata(geometry, p.create_rois, p.roi_geometry)
    """
    if geometry is not None and create_rois and len(geometry) > 1:
        geometry.attrs["create_rois"] = True
        if roi_geometry is None:
            roi_geometry = sigima.enums.DetectionROIGeometry.RECTANGLE
        # Store as string value for HDF5 serialization compatibility
        geometry.attrs["roi_geometry"] = roi_geometry.value
    return geometry


def apply_detection_rois(
    obj: ImageObj,
    geometry: GeometryResult,
    force: bool = False,
    roi_geometry: sigima.enums.DetectionROIGeometry | None = None,
) -> bool:
    """Apply ROI creation from detection geometry result.

    This function checks if the geometry result contains ROI creation metadata
    and applies it to the image object by creating ROIs around detected features.

    Args:
        obj: Image object to modify
        geometry: Geometry result from a detection function
        force: If True, create ROIs even if not requested in the result attrs
        roi_geometry: Override ROI geometry from attrs (if None, uses attrs value)

    Returns:
        True if ROIs were created, False otherwise

    Example:
        >>> from sigima.proc.image import peak_detection, apply_detection_rois
        >>> from sigima.params import Peak2DDetectionParam
        >>> param = Peak2DDetectionParam()
        >>> param.create_rois = True
        >>> geometry = peak_detection(img, param)
        >>> apply_detection_rois(img, geometry)  # Creates ROIs on img
    """
    if geometry is None:
        return False

    # Check if ROI creation was requested (or forced)
    create_rois = force or geometry.attrs.get("create_rois", False)

    if not create_rois or len(geometry) < 2:
        return False

    # Get ROI geometry from parameter, attrs, or use default
    if roi_geometry is None:
        roi_geometry = geometry.attrs.get(
            "roi_geometry",
            sigima.enums.DetectionROIGeometry.RECTANGLE,
        )

    # Get detection coordinates (centers of detected objects)
    coords = geometry.centers()

    try:
        obj.roi = create_image_roi_around_points(coords, roi_geometry=roi_geometry)
        return True
    except ValueError:
        return False


class GenericDetectionParam(gds.DataSet):
    """Generic detection parameters"""

    threshold = gds.FloatItem(
        _("Relative threshold"),
        default=0.5,
        min=0.1,
        max=0.9,
        help=_(
            "Detection threshold, relative to difference between "
            "data maximum and minimum"
        ),
    )


class Peak2DDetectionParam(DetectionROIParam, GenericDetectionParam):
    """Peak detection parameters"""

    size = gds.IntItem(
        _("Neighborhoods size"),
        default=None,
        check=False,  # Allow None value
        min=1,
        unit="pixels",
        help=_(
            "Size of the sliding window used in maximum/minimum filtering algorithm "
            "(if no value is provided, the algorithm will use a default size "
            "based on the image size). "
        ),
    )


@computation_function()
def peak_detection(obj: ImageObj, p: Peak2DDetectionParam) -> GeometryResult | None:
    """Compute 2D peak detection
    with :py:func:`sigima.tools.image.get_2d_peaks_coords`

    Args:
        obj: input image
        p: parameters

    Returns:
        Peak coordinates (with ROI creation info in attrs if requested)
    """
    geometry = compute_geometry_from_obj(
        "peak",
        KindShape.POINT,
        obj,
        sigima.tools.image.get_2d_peaks_coords,
        p.size,
        p.threshold,
    )
    return store_roi_creation_metadata(geometry, p.create_rois, p.roi_geometry)


class ContourShapeParam(GenericDetectionParam):
    """Contour shape parameters"""

    # Keep choices aligned with supported geometry kinds
    assert set(item.name for item in sigima.enums.ContourShape).issubset(
        set(item.name for item in KindShape)
    )
    shape = gds.ChoiceItem(_("Shape"), sigima.enums.ContourShape)


@computation_function()
def contour_shape(image: ImageObj, p: ContourShapeParam) -> GeometryResult | None:
    """Compute contour shape with :py:func:`sigima.tools.image.get_contour_shapes`."""
    shape: sigima.enums.ContourShape = p.shape
    kindshape = getattr(KindShape, shape.name)
    geometry = compute_geometry_from_obj(
        "contour",
        kindshape,
        image,
        sigima.tools.image.get_contour_shapes,
        shape,
        p.threshold,
    )
    return geometry


class BaseBlobParam(gds.DataSet):
    """Base class for blob detection parameters"""

    min_sigma = gds.FloatItem(
        "σ<sub>min</sub>",
        default=10.0,
        unit="pixels",
        min=0,
        nonzero=True,
        help=_(
            "The minimum standard deviation for Gaussian Kernel. "
            "Keep this low to detect smaller blobs."
        ),
    )
    max_sigma = gds.FloatItem(
        "σ<sub>max</sub>",
        default=30.0,
        unit="pixels",
        min=0,
        nonzero=True,
        help=_(
            "The maximum standard deviation for Gaussian Kernel. "
            "Keep this high to detect larger blobs."
        ),
    )
    threshold_rel = gds.FloatItem(
        _("Relative threshold"),
        default=0.2,
        min=0.0,
        max=1.0,
        help=_("Minimum intensity of blobs."),
    )
    overlap = gds.FloatItem(
        _("Overlap"),
        default=0.5,
        min=0.0,
        max=1.0,
        help=_(
            "If two blobs overlap by a fraction greater than this value, the "
            "smaller blob is eliminated."
        ),
    )


class BlobDOGParam(DetectionROIParam, BaseBlobParam):
    """Blob detection using Difference of Gaussian method"""

    exclude_border = gds.BoolItem(
        _("Exclude border"),
        default=True,
        help=_("If True, exclude blobs from the border of the image."),
    )


@computation_function()
def blob_dog(image: ImageObj, p: BlobDOGParam) -> GeometryResult | None:
    """Compute blobs using Difference of Gaussian method
    with :py:func:`sigima.tools.image.find_blobs_dog`

    Args:
        imageOutput: input image
        p: parameters

    Returns:
        Blobs coordinates (with ROI creation info in attrs if requested)
    """
    geometry = compute_geometry_from_obj(
        "blob_dog",
        KindShape.CIRCLE,
        image,
        sigima.tools.image.find_blobs_dog,
        p.min_sigma,
        p.max_sigma,
        p.overlap,
        p.threshold_rel,
        p.exclude_border,
    )
    return store_roi_creation_metadata(geometry, p.create_rois, p.roi_geometry)


class BlobDOHParam(DetectionROIParam, BaseBlobParam):
    """Blob detection using Determinant of Hessian method"""

    log_scale = gds.BoolItem(
        _("Log scale"),
        default=False,
        help=_(
            "If set intermediate values of standard deviations are interpolated "
            "using a logarithmic scale to the base 10. "
            "If not, linear interpolation is used."
        ),
    )


@computation_function()
def blob_doh(image: ImageObj, p: BlobDOHParam) -> GeometryResult | None:
    """Compute blobs using Determinant of Hessian method
    with :py:func:`sigima.tools.image.find_blobs_doh`

    Args:
        imageOutput: input image
        p: parameters

    Returns:
        Blobs coordinates (with ROI creation info in attrs if requested)
    """
    geometry = compute_geometry_from_obj(
        "blob_doh",
        KindShape.CIRCLE,
        image,
        sigima.tools.image.find_blobs_doh,
        p.min_sigma,
        p.max_sigma,
        p.overlap,
        p.log_scale,
        p.threshold_rel,
    )
    return store_roi_creation_metadata(geometry, p.create_rois, p.roi_geometry)


class BlobLOGParam(BlobDOHParam):
    """Blob detection using Laplacian of Gaussian method"""

    exclude_border = gds.BoolItem(
        _("Exclude border"),
        default=True,
        help=_("If True, exclude blobs from the border of the image."),
    )


@computation_function()
def blob_log(image: ImageObj, p: BlobLOGParam) -> GeometryResult | None:
    """Compute blobs using Laplacian of Gaussian method
    with :py:func:`sigima.tools.image.find_blobs_log`

    Args:
        imageOutput: input image
        p: parameters

    Returns:
        Blobs coordinates (with ROI creation info in attrs if requested)
    """
    geometry = compute_geometry_from_obj(
        "blob_log",
        KindShape.CIRCLE,
        image,
        sigima.tools.image.find_blobs_log,
        p.min_sigma,
        p.max_sigma,
        p.overlap,
        p.log_scale,
        p.threshold_rel,
        p.exclude_border,
    )
    return store_roi_creation_metadata(geometry, p.create_rois, p.roi_geometry)


class BlobOpenCVParam(DetectionROIParam, gds.DataSet):
    """Blob detection using OpenCV"""

    min_threshold = gds.FloatItem(
        _("Min. threshold"),
        default=10.0,
        min=0.0,
        help=_(
            "The minimum threshold between local maxima and minima. "
            "This parameter does not affect the quality of the blobs, "
            "only the quantity. Lower thresholds result in larger "
            "numbers of blobs."
        ),
    )
    max_threshold = gds.FloatItem(
        _("Max. threshold"),
        default=200.0,
        min=0.0,
        help=_(
            "The maximum threshold between local maxima and minima. "
            "This parameter does not affect the quality of the blobs, "
            "only the quantity. Lower thresholds result in larger "
            "numbers of blobs."
        ),
    )
    min_repeatability = gds.IntItem(
        _("Min. repeatability"),
        default=2,
        min=1,
        help=_(
            "The minimum number of times a blob needs to be detected "
            "in a sequence of images to be considered valid."
        ),
    )
    min_dist_between_blobs = gds.FloatItem(
        _("Min. distance between blobs"),
        default=10.0,
        min=0.0,
        nonzero=True,
        help=_(
            "The minimum distance between two blobs. If blobs are found "
            "closer together than this distance, the smaller blob is removed."
        ),
    )
    _prop_col = gds.ValueProp(False)
    filter_by_color = gds.BoolItem(
        _("Filter by color"),
        default=True,
        help=_("If true, the image is filtered by color instead of intensity."),
    ).set_prop("display", store=_prop_col)
    blob_color = gds.IntItem(
        _("Blob color"),
        default=0,
        help=_(
            "The color of the blobs to detect (0 for dark blobs, 255 for light blobs)."
        ),
    ).set_prop("display", active=_prop_col)
    _prop_area = gds.ValueProp(False)
    filter_by_area = gds.BoolItem(
        _("Filter by area"),
        default=True,
        help=_("If true, the image is filtered by blob area."),
    ).set_prop("display", store=_prop_area)
    min_area = gds.FloatItem(
        _("Min. area"),
        default=25.0,
        min=0.0,
        help=_("The minimum blob area."),
    ).set_prop("display", active=_prop_area)
    max_area = gds.FloatItem(
        _("Max. area"),
        default=500.0,
        min=0.0,
        help=_("The maximum blob area."),
    ).set_prop("display", active=_prop_area)
    _prop_circ = gds.ValueProp(False)
    filter_by_circularity = gds.BoolItem(
        _("Filter by circularity"),
        default=False,
        help=_("If true, the image is filtered by blob circularity."),
    ).set_prop("display", store=_prop_circ)
    min_circularity = gds.FloatItem(
        _("Min. circularity"),
        default=0.8,
        min=0.0,
        max=1.0,
        help=_("The minimum circularity of the blobs."),
    ).set_prop("display", active=_prop_circ)
    max_circularity = gds.FloatItem(
        _("Max. circularity"),
        default=1.0,
        min=0.0,
        max=1.0,
        help=_("The maximum circularity of the blobs."),
    ).set_prop("display", active=_prop_circ)
    _prop_iner = gds.ValueProp(False)
    filter_by_inertia = gds.BoolItem(
        _("Filter by inertia"),
        default=False,
        help=_("If true, the image is filtered by blob inertia."),
    ).set_prop("display", store=_prop_iner)
    min_inertia_ratio = gds.FloatItem(
        _("Min. inertia ratio"),
        default=0.6,
        min=0.0,
        max=1.0,
        help=_("The minimum inertia ratio of the blobs."),
    ).set_prop("display", active=_prop_iner)
    max_inertia_ratio = gds.FloatItem(
        _("Max. inertia ratio"),
        default=1.0,
        min=0.0,
        max=1.0,
        help=_("The maximum inertia ratio of the blobs."),
    ).set_prop("display", active=_prop_iner)
    _prop_conv = gds.ValueProp(False)
    filter_by_convexity = gds.BoolItem(
        _("Filter by convexity"),
        default=False,
        help=_("If true, the image is filtered by blob convexity."),
    ).set_prop("display", store=_prop_conv)
    min_convexity = gds.FloatItem(
        _("Min. convexity"),
        default=0.8,
        min=0.0,
        max=1.0,
        help=_("The minimum convexity of the blobs."),
    ).set_prop("display", active=_prop_conv)
    max_convexity = gds.FloatItem(
        _("Max. convexity"),
        default=1.0,
        min=0.0,
        max=1.0,
        help=_("The maximum convexity of the blobs."),
    ).set_prop("display", active=_prop_conv)


@computation_function()
def blob_opencv(image: ImageObj, p: BlobOpenCVParam) -> GeometryResult | None:
    """Compute blobs using OpenCV
    with :py:func:`sigima.tools.image.find_blobs_opencv`

    Args:
        imageOutput: input image
        p: parameters

    Returns:
        Blobs coordinates (with ROI creation info in attrs if requested)
    """
    geometry = compute_geometry_from_obj(
        "blob_opencv",
        KindShape.CIRCLE,
        image,
        sigima.tools.image.find_blobs_opencv,
        p.min_threshold,
        p.max_threshold,
        p.min_repeatability,
        p.min_dist_between_blobs,
        p.filter_by_color,
        p.blob_color,
        p.filter_by_area,
        p.min_area,
        p.max_area,
        p.filter_by_circularity,
        p.min_circularity,
        p.max_circularity,
        p.filter_by_inertia,
        p.min_inertia_ratio,
        p.max_inertia_ratio,
        p.filter_by_convexity,
        p.min_convexity,
        p.max_convexity,
    )
    return store_roi_creation_metadata(geometry, p.create_rois, p.roi_geometry)


class HoughCircleParam(DetectionROIParam, gds.DataSet):
    """Circle Hough transform parameters"""

    min_radius = gds.IntItem(
        _("Radius<sub>min</sub>"), unit="pixels", min=0, nonzero=True
    )
    max_radius = gds.IntItem(
        _("Radius<sub>max</sub>"), unit="pixels", min=0, nonzero=True
    )
    min_distance = gds.IntItem(_("Minimal distance"), min=0)


@computation_function()
def hough_circle_peaks(image: ImageObj, p: HoughCircleParam) -> GeometryResult | None:
    """Compute Hough circles
    with :py:func:`sigima.tools.image.get_hough_circle_peaks`

    Args:
        image: input image
        p: parameters

    Returns:
        Circle coordinates (with ROI creation info in attrs if requested)
    """
    geometry = compute_geometry_from_obj(
        "hough_circle_peak",
        KindShape.CIRCLE,
        image,
        sigima.tools.image.get_hough_circle_peaks,
        p.min_radius,
        p.max_radius,
        None,
        p.min_distance,
    )
    return store_roi_creation_metadata(geometry, p.create_rois, p.roi_geometry)