-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathimage.py
1886 lines (1430 loc) · 56.6 KB
/
image.py
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Containers for array-like structures.
This module defines the `Image` class and related utility functions for
managing array-like structures and their associated properties. The `Image`
class is central to DeepTrack2, acting as a container for numerical data
(such as images, tensors, and scalars) while maintaining the properties
generated by features during pipeline processing.
Key Features
------------
- **Enhanced Array-Like Interface**
The `Image` class provides an interface similar to NumPy arrays, enabling
mathematical operations, slicing, and indexing, while preserving additional
metadata as properties.
- **Property Management**
`Image` objects store properties that describe the transformations and
features applied during their creation, ensuring traceability and enabling
advanced functionality.
- **Interoperability**
Includes seamless integration with NumPy, CuPy, and PyTorch arrays,
allowing for GPU acceleration and deep learning compatibility.
- **Utility Functions**
Includes helper functions (`coerce`, `strip`, etc.) for managing and
manipulating `Image` objects efficiently within pipelines.
Key Classes
-----------
- `Image`: Core class for managing array-like data and their properties.
Encapsulates array-like data structures (e.g., NumPy arrays, lists,
Torch tensors) while providing a unified interface for array operations and
property management.
Methods
-------
- `strip(element)`
strip(
element: Image | np.ndarray | list | tuple | Any,
) -> Any
Recursively extract the underlying value from an Image object.
- `coerce(images)`
coerce(
images: list[Image | np.ndarray],
) -> list[Image]
Coerce a list of images to a consistent type.
- `pad_image_to_fft(image, axes)`
pad_image_to_fft(
image: Image | np.ndarray,
axes: Iterable[int] = (0, 1),
) -> Image | np.ndarray
Pads an image to optimize Fast Fourier Transform (FFT) performance.
- `maybe_cupy(array)`
maybe_cupy(
array: np.ndarray | list | tuple,
) -> cupy.ndarray | np.ndarray
Convert an array to a CuPy array if GPU is available and enabled.
Examples
--------
Basic usage of the `Image` class:
>>> import numpy as np
>>> from deeptrack.image import Image
>>> img = Image(np.array([[1, 2], [3, 4]]))
>>> print(img + 1)
Image([[2, 3],
[4, 5]])
Property tracking:
>>> from deeptrack.properties import Property
>>> img.append({"feature": "example", "value": 42})
>>> print(img.properties)
[{'feature': 'example', 'value': 42}]
"""
from __future__ import annotations
import operator as ops
from typing import Any, Callable, Iterable
import numpy as np
from deeptrack.backend._config import cupy
from deeptrack.properties import Property
from deeptrack.types import NumberLike
def _binary_method(
op: Callable[[NumberLike, NumberLike], NumberLike],
) -> Callable[[Image, Image | NumberLike], Image]:
"""Implement a binary operator for the Image class.
This function generates a binary method (e.g., `__add__`, `__sub__`) for
the `Image` class, enabling operations like addition, subtraction, or
comparison between `Image` objects or between an `Image` object and a
scalar/array. It operates between the operands `self`and `other`.
The resulting method applies the specified operator (`op`) to the `_value`
attribute of the `Image` object, preserving the `Image` structure and its
properties.
If the `other` operand is also an `Image` object, the resulting `Image`
merges the properties of both operands.
If the `other` operand is not an `Image`, it is treated as a scalar or
array, and only the properties of `self` are preserved in the resulting
`Image`.
Parameters
----------
op: Callable[[NumberLike, NumberLike], NumberLike]
The operator function (e.g., `operator.add`, `operator.sub`) that
defines the binary operation.
Returns
-------
Callable[[Image, Image | NumberLike], Image]
A method that can be assigned to a binary operator (e.g., `__add__`)
of the `Image` class.
Examples
--------
>>> import operator
>>> import numpy as np
>>> from deeptrack.image import _binary_method, Image
Define __add__ for the Image class:
>>> Image.__add__ = _binary_method(operator.add)
Create two images and add them:
>>> img1 = Image(np.array([1, 2, 3]))
>>> img2 = Image(np.array([4, 5, 6]))
>>> result = img1 + img2
>>> print(result)
Image(array([5, 7, 9]))
Add a scalar to an Image:
>>> result = img1 + 10
>>> print(result)
Image(array([11, 12, 13]))
"""
def func(
self: Image | np.ndarray,
other: Image | np.ndarray | NumberLike,
) -> Image:
# Coerce inputs to compatible types.
self, other = coerce([self, other])
if isinstance(other, Image):
# Perform operation and merge properties from both Images.
return Image(
op(self._value, other._value),
copy=False,
).merge_properties_from([self, other])
else:
# Perform operation and retain properties from `self`.
return Image(
op(self._value, other),
copy=False,
).merge_properties_from(self)
func.__name__ = f"__{op.__name__}__"
return func
def _reflected_binary_method(
op: Callable[[NumberLike, NumberLike], NumberLike],
) -> Callable[[Image | NumberLike, Image], Image]:
"""Implement a reflected binary operator for the Image class.
This function generates a reflected binary method (e.g., `__radd__`,
`__rsub__`) for the `Image` class, enabling operations like reverse
addition or subtraction between an `Image` object and another operand
(scalar, array, or `Image`). This method is invoked when the left-hand
operand does not implement the operation for the provided types.
The resulting method applies the specified operator (`op`) in reverse
order, where the `other` operand is treated as the left-hand operand and
`self` is treated as the right-hand operand.
If the `other` operand is also an `Image` object, the resulting `Image`
merges the properties of both operands.
If the `other` operand is not an `Image`, it is treated as a scalar or
array, and only the properties of `self` are preserved in the resulting
`Image`.
Parameters
----------
op: Callable[[NumberLike, NumberLike], NumberLike]
The operator function (e.g., `operator.add`, `operator.sub`) that
defines the reflected binary operation.
Returns
-------
Callable[[Image, Image | NumberLike], Image]
A method that can be assigned to a reflected binary operator (e.g.,
`__radd__`) of the `Image` class.
Examples
--------
>>> import operator
>>> import numpy as np
>>> from deeptrack.image import _reflected_binary_method, Image
Define __radd__ for the Image class:
>>> Image.__radd__ = _reflected_binary_method(operator.add)
Add an Image to a scalar (reflected operation):
>>> img = Image(np.array([1, 2, 3]))
>>> result = 10 + img
>>> print(result)
Image(array([11, 12, 13]))
Add two Images (reflected operation):
>>> img2 = Image(np.array([4, 5, 6]))
>>> result = img2 + img
>>> print(result)
Image(array([5, 7, 9]))
"""
def func(
self: Image | np.ndarray,
other: Image | np.ndarray | NumberLike,
) -> Image:
# Coerce inputs to compatible types.
self, other = coerce([self, other])
if isinstance(other, Image):
# Perform operation and merge properties from both Images.
return Image(
op(other._value, self._value),
copy=False,
).merge_properties_from([other, self])
else:
# Perform operation and retain properties from `self`.
return Image(
op(other, self._value),
copy=False,
).merge_properties_from(self)
func.__name__ = f"__r{op.__name__}__"
return func
def _inplace_binary_method(
op: Callable[[NumberLike, NumberLike], NumberLike]
) -> Callable[[Image, Image | NumberLike], Image]:
"""Implement an in-place binary operator for the Image class.
This function generates an in-place binary method (e.g., `__iadd__`,
`__imul__`) for the `Image` class, enabling operations like in-place
addition, multiplication, or other modifications to an `Image` object. The
operation updates the `_value` of the current `Image` instance (`self`)
rather than creating a new one.
The resulting method applies the specified operator (`op`) to the `_value`
attribute of the `Image` object, preserving the `Image` structure and its
properties.
If the `other` operand is also an `Image` object, the properties of `other`
are merged into `self`.
Parameters
----------
op: Callable[[NumberLike, NumberLike], NumberLike]
The operator function (e.g., `operator.iadd`, `operator.imul`) that
defines the in-place binary operation.
Returns
-------
Callable[[Image, Image | NumberLike], None]
A method that can be assigned to an in-place binary operator (e.g.,
`__iadd__`) of the `Image` class.
Examples
--------
>>> import operator
>>> import numpy as np
>>> from deeptrack.image import _inplace_binary_method, Image
Define __iadd__ for the Image class:
>>> Image.__iadd__ = _inplace_binary_method(operator.iadd)
Create two images and perform in-place addition:
>>> img1 = Image(np.array([1, 2, 3]))
>>> img2 = Image(np.array([4, 5, 6]))
>>> img1 += img2
>>> print(img1)
Image(array([5, 7, 9]))
Add a scalar to an Image in-place:
>>> img1 += 10
>>> print(img1)
Image(array([15, 17, 19]))
"""
def func(
self: Image | np.ndarray,
other: Image | np.ndarray | NumberLike,
) -> Image:
# Coerce inputs to compatible types.
self, other = coerce([self, other])
if isinstance(other, Image):
# Perform in-place operation and merge properties from `other`.
self._value = op(self._value, other._value)
self.merge_properties_from(other)
else:
# Perform in-place operation without merging properties.
self._value = op(self._value, other)
return self
func.__name__ = f"__i{op.__name__}__"
return func
def _numeric_methods(
op: Callable[[NumberLike, NumberLike], NumberLike],
) -> tuple[
Callable[[Image, Image | NumberLike], Image],
Callable[[Image | NumberLike, Image], Image],
Callable[[Image, Image | NumberLike], Image]
]:
"""Generate forward, reflected, and in-place binary methods.
This utility function returns a tuple of three methods that implement
forward (e.g., `__add__`), reflected (e.g., `__radd__`), and in-place
(e.g., `__iadd__`) binary operations for a given numeric operator.
These methods are generated using `_binary_method`,
`_reflected_binary_method`, and `_inplace_binary_method` respectively,
which handle the specific semantics of each type of operation.
Parameters
----------
op: Callable[[NumberLike, NumberLike], NumberLike]
A callable representing the numeric operator (e.g., `operator.add`,
`operator.mul`) to implement the methods for.
Returns
-------
tuple[
Callable[[Image, Image | NumberLike], Image],
Callable[[Image | NumberLike, Image], Image],
Callable[[Image, Image | NumberLike], Image]
]
A tuple containing three callables:
(1) The forward binary method (`_binary_method`).
(2) The reflected binary method (`_reflected_binary_method`).
(3) The in-place binary method (`_inplace_binary_method`).
Examples
--------
>>> import operator
>>> from deeptrack.image import _numeric_methods, Image
Define addition methods for the Image class:
>>> Image.__add__, Image.__radd__, Image.__iadd__ = \
... _numeric_methods(operator.add)
Perform forward, reflected, and in-place addition:
>>> img1 = Image([1, 2, 3])
>>> img2 = Image([4, 5, 6])
Forward addition:
>>> result = img1 + img2
>>> print(result)
Image(array([5, 7, 9]))
Reflected addition:
>>> result = [10, 20, 30] + img1
>>> print(result)
Image(array([11, 22, 33]))
In-place addition:
>>> img1 += img2
>>> print(img1)
Image(array([5, 7, 9]))
"""
return (
_binary_method(op),
_reflected_binary_method(op),
_inplace_binary_method(op),
)
def _unary_method(
op: Callable[[NumberLike], NumberLike],
) -> Callable[[Image], Image]:
"""Implement a unary special method for the Image class.
This function generates a unary method (e.g., `__neg__`, `__abs__`) for
the `Image` class. It applies the specified unary operator (`op`) to the
`_value` attribute of the `Image` instance while preserving the `Image`
structure and its properties.
Parameters
----------
op: Callable[[NumberLike], NumberLike]
A callable representing the unary operation (e.g., `operator.neg`,
`operator.abs`).
Returns
-------
Callable[[Image], Image]
A method that can be assigned to a unary operator (e.g., `__neg__`)
of the `Image` class.
Examples
--------
>>> import operator
>>> import numpy as np
>>> from deeptrack.image import _unary_method, Image
Define negation for the Image class:
>>> Image.__neg__ = _unary_method(operator.neg)
Create an image and apply negation:
>>> img = Image(np.array([1, 2, 3]))
>>> result = -img
>>> print(result)
Image(array([-1, -2, -3]))
"""
def func(
self: Image | np.ndarray,
) -> Image:
# Apply the unary operator to the Image instance.
return Image(
op(self._value)
).merge_properties_from(self)
func.__name__ = f"__{op}__"
return func
class Image:
"""Wrapper for array-like values with property tracking.
This class encapsulates array-like values (e.g., NumPy arrays, lists,
tensors) while providing a unified interface for array operations and
property management.
It serves two primary purposes:
1. **Unified Interface**
Offers compatibility with NumPy and CuPy operations regardless of the
underlying data type. This allows for seamless integration with NumPy
functions and universal function calls (`ufuncs`).
2. **Property Tracking**
Stores and manages properties associated with features used in creating
or modifying the image. This makes it possible to track metadata and
ensure consistency across operations.
Attributes
----------
_value: np.ndarray
The underlying data stored in the Image object as NumPy.
properties: list[dict[str, Property]]
A list of property dictionaries associated with the Image.
Parameters
----------
value: np.ndarray | list | int | float | bool | Image
The array-like object to be converted to a NumPy array and stored in
the Image object. If it is an Image, the value and properties of the
image are copied or referenced depening on the value of the `copy`
parameter.
copy: bool, optional
If `True`, the `value` is copied to ensure independence (default).
If `False`, a reference to the original value is maintained.
Methods
-------
**Property Management**
`append(
property_dict: dict
) -> Image`
Add a dictionary of properties to the `Image`.
`get_property(
key: str,
get_one: bool = True,
default: Any = None
) -> Any | list[Any]`
Retrieve a property by key. If `get_one` is `True`, returns the first
match; otherwise, returns a list of matches.
`merge_properties_from(
other: Image | list[Image] | np.ndarray | list[np.ndarray]
) -> Image`
Merge properties from another `Image`, list of `Image`s, or a NumPy
array.
**Conversion Utilities**
`to_cupy() -> Image`
Convert the `Image` to a CuPy array if the underlying value is a NumPy
array.
`to_numpy() -> Image`
Convert the `Image` to a numpy array if the underlying value is a CuPy
array.
`__array__(*args: tuple[Any, ...], **kwargs: dict[str, Any]) -> np.ndarray`
Convert the `Image` to a numpy array. Used implicitly by numpy functions.
**NumPy Compatibility
`__array_ufunc__(
ufunc: Callable,
method: str,
*inputs: tuple[Any],
**kwargs: dict[str, Any]
) -> Image | tuple[Image, ...] | None`
Enable compatibility with numpy's universal functions (ufuncs).
Examples include `np.add`, `np.multiply`, and `np.sin`.
The following NumPy universal functions (ufuncs) are supported:
- Arithmetic:
`np.add`, `np.subtract`, `np.multiply`, `np.divide`, `np.power`,
`np.mod`, etc.
- Trigonometric:
`np.sin`, `np.cos`, `np.tan`, `np.arcsin`, `np.arccos`,
`np.arctan`, etc.
- Exponential and logarithmic:
`np.exp`, `np.log`, `np.log10`, etc.
- Comparison:
`np.equal`, `np.not_equal`, `np.less`, `np.less_equal`,
`np.greater`, `np.greater_equal`, etc.
- Bitwise:
`np.bitwise_and`, `np.bitwise_or`, `np.bitwise_xor`, etc.
`__array_function__(
func: Callable[..., Any],
types: tuple[type, ...],
args: tuple[Any, ...],
kwargs: dict[str, Any]
) -> Image | tuple[Image, ...] | Any`
Enable compatibility with numpy's general functions, such as `np.mean`,
`np.dot`, and `np.concatenate`.
The following numpy general functions are supported:
- Array manipulation:
`np.reshape`, `np.transpose`, `np.concatenate`, etc.
- Statistical:
`np.mean`, `np.sum`, `np.std`, etc.
- Linear algebra:
`np.dot`, `np.cross`, etc.
**Indexing and Assignment**
`__getitem__(
idx: Any
) -> Image | Any`
Access array elements using standard indexing or slicing. If the result
is scalar, returns it; otherwise, returns an `Image`.
`__setitem__(
key: Any,
value: Any
) -> None`
Assign values to specific array elements. Updates the properties of the
`Image` accordingly.
**Special Methods**
`__repr__() -> str`
Return a string representation of the `Image` object.
Examples
--------
Create an `Image` instance from a NumPy array:
>>> import numpy as np
>>> from deeptrack.image import Image
>>> img = Image(np.array([[1, 2], [3, 4]]))
>>> print(img)
Image(array([[1, 2],
[3, 4]]))
Access NumPy attributes and methods:
>>> print(img.shape)
(2, 2)
>>> print(img.sum())
10
Manage properties:
>>> img.append({"property_name": "example"})
>>> print(img.properties)
[{'property_name': 'example'}]
Compatibility with NumPy ufuncs:
>>> print(img + 10)
Image(array([[11, 12],
[13, 14]]))
Conversion between NumPy and CuPy arrays:
>>> import cupy
>>> gpu_img = img.to_cupy()
>>> print(type(gpu_img._value))
<class cupy.ndarray>
>>> converted_back = gpu_img.to_numpy()
>>> print(type(converted_back._value))
<class 'numpy.ndarray'>
"""
# Attributes.
_value: np.ndarray
properties: list[dict[str, Property]]
def __init__(
self: Image | np.ndarray,
value: Image | np.ndarray | list | int | float | bool,
copy: bool = True,
):
"""Initialize an Image object.
The `Image` class wraps an array-like object, providing enhanced
functionality such as property tracking and compatibility with NumPy
and CuPy operations.
Parameters
----------
value: np.ndarray | list | int | float | bool | Image
The array-like object to be converted to a NumPy array and stored
in the Image object. If it is an Image, the value and properties of
the image are copied or referenced depening on the value of the
`copy` parameter.
copy: bool, optional
If `True`, the `value` is copied to ensure independence (default).
If `False`, a reference to the original value is maintained.
Attributes
----------
_value: np.ndarray
The underlying data stored in the Image object as NumPy.
properties: list[dict[str, Property]]
A list of property dictionaries associated with the Image.
"""
super().__init__()
# Copy the value if requested, otherwise use a reference.
if copy:
self._value = self._view(value)
else:
if isinstance(value, Image):
self._value = value._value
else:
self._value = value
# Copy properties from the input Image if applicable,
# otherwise initialize an empty list
if isinstance(value, Image):
self.properties = list(value.properties)
else:
self.properties = []
def append(
self: Image | np.ndarray,
property_dict: dict[str, Property],
) -> Image:
"""Append a dictionary to the properties list.
This method adds a dictionary of property values to the `properties`
list of the `Image` instance.
This method does not ensure uniqueness of properties within the
`properties` list. Duplicate entries may be added if the same
dictionary is appended multiple times.
Parameters
----------
property_dict: dict[str, Property]
A dictionary to append to the property list.
Returns
-------
Image
Returns itself.
Examples
--------
>>> import numpy as np
>>> from deeptrack import Feature, Image
Define the feature and enable property storage:
>>> class SimpleParticle(Feature):
... def get(self, image, position=None, **kwargs):
... return image
>>> particle = SimpleParticle(position=(128, 128))
>>> particle.store_properties() # Return Image instead of NumPy array.
Create an input image and resolve the feature:
>>> input_image = Image(np.zeros((256, 256)))
>>> output_image = particle.resolve(input_image)
>>> print(output_image.properties)
[{'position': (128, 128), 'name': 'SimpleParticle'}]
Append new properties to the image:
>>> output_image.append({"key1": 1, "key2": 2})
>>> print(output_image.properties)
[{'position': (128, 128), 'name': 'SimpleParticle'},
{'key1': 1, 'key2': 2}]
"""
#TODO: Check if we still need to make a copy of the list.
self.properties = [*self.properties, property_dict]
return self
def get_property(
self: Image | np.ndarray,
key: str,
get_one: bool = True,
default: Any = None,
) -> Any | list[Any]:
"""Retrieve the value of a property of the Image.
If the feature has the property defined by `key`, the method returns
its current_value. Otherwise, it returns the `default` value.
If `get_one` is `True`, the first instance is returned; otherwise, all
instances are returned as a list.
Parameters
----------
key: str
The name of the property.
get_one: bool, optional
Whether to return only the first instance of the property (default
behavior for `True`) or all instances of the property (`False`).
default: Any, optional
The value to be returned as default, which is by default `None`.
Returns
-------
Any | list[Any]
The value of the property (if `get_one` is `True`) or all instances
as a list (if `get_one` is `True`). If the property is not found,
it returns `default`.
Examples
--------
>>> import numpy as np
>>> from deeptrack import Feature, Image
Define the feature and enable property storage:
>>> class SimpleParticle(Feature):
... def get(self, image, position=None, **kwargs):
... return image
>>> particle = SimpleParticle(position=(128, 128))
>>> particle.store_properties() # Return Image instead of NumPy array.
Create an input image and resolve the feature:
>>> input_image = Image(np.zeros((256, 256)))
>>> output_image = particle.resolve(input_image)
Retrieve the properties:
>>> print(output_image.get_property("position"))
>>> print(output_image.get_property("name"))
"""
# If get_one = True, return the first instance of the property.
if get_one:
for prop in self.properties:
if key in prop:
return prop[key]
# If no instance, return the default.
return default
# If get_one = False, return all instances of the property,
# or default if no instance of the property.
return [
prop[key]
for prop
in self.properties
if key in prop
] or default
def merge_properties_from(
self: Image | np.ndarray,
other: np.ndarray | Image | Iterable,
) -> Image:
"""Merge properties with those from another Image.
Appends properties from another images without duplicating properties.
The uniqueness of a dictionary of properties is determined from the
property `hash_key`.
Most functions involving two images should automatically output an
image with merged properties. However, since each property is
guaranteed to be unique, it is safe to manually call this function if
there is any uncertainty.
Parameters
----------
other: Image | np.ndarray | Iterable
The data to retrieve properties from. It can be an Image, a NumPy
array (which has no properties), or an iterable object.
Returns
-------
Image
Returns itself.
Examples
--------
>>> import numpy as np
>>> from deeptrack import Feature, Image
Define the feature and enable property storage:
>>> class SimpleParticle(Feature):
... def get(self, image, position=None, **kwargs):
... return image
>>> particle = SimpleParticle(position=(128, 128))
>>> particle.store_properties() # To return an Image and not an array.
Create an input image:
>>> input_image = Image(np.zeros((256, 256)))
Resolve the feature twice without update and verify that only one set
of properties is stored:
>>> output_image1 = particle.resolve(input_image)
>>> output_image2 = particle.resolve(input_image)
>>> output_image1.merge_properties_from(output_image2)
>>> print(output_image1.properties)
[{'position': (128, 128), 'name': 'SimpleParticle'}]
Update the feature, resolve it, and verify that now two sets of
properties are stored:
>>> particle.update()
>>> output_image3 = particle.resolve(input_image)
>>> output_image1.merge_properties_from(output_image3)
>>> print(output_image1.properties)
[{'position': (128, 128), 'name': 'SimpleParticle'},
{'position': (128, 128), 'name': 'SimpleParticle'}]
Now, call the method with a list including a previously merged feature
and a NumPy array that are not merged:
>>> particle.update()
>>> output_image4 = particle.resolve(input_image)
>>> output_image1.merge_properties_from(
... [output_image3, output_image4, np.zeros((10, 10))]
... )
>>> print(output_image1.properties)
[{'position': (128, 128), 'name': 'SimpleParticle'},
{'position': (128, 128), 'name': 'SimpleParticle'},
{'position': (128, 128), 'name': 'SimpleParticle'}]
"""
# If other is a NumPy array, return the image itself,
# because arrays can not contain properties.
if isinstance(other, np.ndarray):
return self
# If other is an Image, add the properties without duplication.
if isinstance(other, Image):
for new_prop in other.properties:
# Check if the property is already in the list.
should_append = True
for my_prop in self.properties:
if my_prop is new_prop:
# Prop already present.
should_append = False
break
# Append new property if not duplicated.
if should_append:
self.append(new_prop)
return self
# Ensure that the recursion is not infinite.
if not isinstance(other, str):
# If other is iterable, recurse.
if hasattr(other, "__iter__"):
for item in other:
self.merge_properties_from(item)
return self
# Return the Image itself unaltered.
return self
def _view(
self: Image | np.ndarray,
value: Image | np.ndarray | list | int | float | bool,
) -> np.ndarray:
"""Convert the value to NumPy array for storage in the Image object.
This method converts the value to a NumPy array to ensure that the
stored value is compatible with the `Image` class.
If the input is a list or scalar type, it is converted into a NumPy
array.
If the input is another `Image` object, it recursively retrieves the
underlying value to avoid nesting.
If the input is not compatible with NumPy array conversion, the
original value is returned.
Parameters
----------
value: np.ndarray | list | int | float | bool | Image
The input value to be transformed to a NumPy array.
Returns
-------
np.ndarray
A NumPy array representation of the input value. If the input is
not compatible with NumPy array conversion, the original value is
returned.