22from __future__
import annotations
25from typing
import Any, Callable, Sequence, cast
28from numpy.typing
import DTypeLike
31from .utils
import ScalarLike, ScalarTypes
33__all__ = [
"Image",
"MismatchedBoxError",
"MismatchedBandsError"]
37 """Attempt to compare images with different bands"""
41 """Attempt to compare images in different bounding boxes"""
44def get_dtypes(*data: np.ndarray | Image | ScalarLike) -> list[DTypeLike]:
45 """Get a list of dtypes from a list of arrays, images, or scalars
50 The arrays to use for calculating the dtype
57 dtypes: list[DTypeLike] = [
None] * len(data)
58 for d, element
in enumerate(data):
59 if hasattr(element,
"dtype"):
60 dtypes[d] = cast(np.ndarray, element).dtype
62 dtypes[d] = np.dtype(type(element))
67 """Get the combined dtype for a collection of arrays to prevent loss
73 The arrays to use for calculating the dtype
85 """A numpy array with an origin and (optional) bands
87 This class contains a 2D numpy array with the addition of an
88 origin (``yx0``) and an optional first index (``bands``) that
89 allows an immutable named index to be used.
93 One of the main limitations of using numpy arrays to store image data
94 is the lack of an ``origin`` attribute that allows an array to retain
95 knowledge of it's location in a larger scene.
96 For example, if a numpy array ``x`` is sliced, eg. ``x[10:20, 30:40]``
97 the result will be a new ``10x10`` numpy array that has no meta
98 data to inform the user that it was sliced from a larger image.
99 In addition, astrophysical images are also multi-band data cubes,
100 with a 2D image in each band (in fact this is the simplifying
101 assumption that distinguishes scarlet lite from scarlet main).
102 However, the ordering of the bands during processing might differ from
103 the ordering of the bands to display multiband data.
104 So a mechanism was also desired to simplify the sorting and index of
105 an image by band name.
107 Thus, scarlet lite creates a numpy-array like class with the additional
108 ``bands`` and ``yx0`` attributes to keep track of the bands contained
109 in an array and the origin of that array (we specify ``yx0`` as opposed
110 to ``xy0`` to be consistent with the default numpy/C++ ``(y, x)``
111 ordering of arrays as opposed to the traditional cartesian ``(x, y)``
112 ordering used in astronomy and other modules in the science pipelines.
113 While this may be a small source of confusion for the user,
114 it is consistent with the ordering in the original scarlet package and
115 ensures the consistency of scarlet lite images and python index slicing.
120 The easiest way to create a new image is to use ``Image(numpy_array)``,
123 >>> import numpy as np
124 >>> from lsst.scarlet.lite import Image
126 >>> x = np.arange(12).reshape(3, 4)
134 bbox=Box(shape=(3, 4), origin=(0, 0))
136 This will create a single band :py:class:`~lsst.scarlet.lite.Image` with
138 To create a multi-band image the input array must have 3 dimensions and
139 the ``bands`` property must be specified:
141 >>> x = np.arange(24).reshape(2, 3, 4)
142 >>> image = Image(x, bands=("i", "z"))
153 bbox=Box(shape=(3, 4), origin=(0, 0))
155 It is also possible to create an empty single-band image using the
156 ``from_box`` static method:
158 >>> from lsst.scarlet.lite import Box
159 >>> image = Image.from_box(Box((3, 4), (100, 120)))
166 bbox=Box(shape=(3, 4), origin=(100, 120))
168 Similarly, an empty multi-band image can be created by passing a tuple
171 >>> image = Image.from_box(Box((3, 4)), bands=("r", "i"))
182 bbox=Box(shape=(3, 4), origin=(0, 0))
184 To select a sub-image use a ``Box`` to select a spatial region in either a
185 single-band or multi-band image:
187 >>> x = np.arange(60).reshape(3, 4, 5)
188 >>> image = Image(x, bands=("g", "r", "i"), yx0=(20, 30))
189 >>> bbox = Box((2, 2), (21, 32))
190 >>> print(image[bbox])
200 bands=('g', 'r', 'i')
201 bbox=Box(shape=(2, 2), origin=(21, 32))
204 To select a single-band image from a multi-band image,
205 pass the name of the band as an index:
207 >>> print(image["r"])
214 bbox=Box(shape=(4, 5), origin=(20, 30))
216 Multi-band images can also be sliced in the spatial dimension, for example
218 >>> print(image["g":"r"])
230 bbox=Box(shape=(4, 5), origin=(20, 30))
234 >>> print(image["r":"r"])
241 bbox=Box(shape=(4, 5), origin=(20, 30))
243 both extract a slice of a multi-band image.
246 Unlike numerical indices, where ``slice(x, y)`` will select the
247 subset of an array from ``x`` to ``y-1`` (excluding ``y``),
248 a spectral slice of an ``Image`` will return the image slice
249 including band ``y``.
251 It is also possible to change the order or index a subset of bands
252 in an image. For example:
254 >>> print(image[("r", "g", "i")])
270 bands=('r', 'g', 'i')
271 bbox=Box(shape=(4, 5), origin=(20, 30))
274 will return a new image with the bands re-ordered.
276 Images can be combined using the standard arithmetic operations similar to
277 numpy arrays, including ``+, -, *, /, **`` etc, however, if two images are
278 combined with different bounding boxes, the _union_ of the two
279 boxes is used for the result. For example:
281 >>> image1 = Image(np.ones((2, 3, 4)), bands=tuple("gr"))
282 >>> image2 = Image(np.ones((2, 3, 4)), bands=tuple("gr"), yx0=(2, 3))
283 >>> result = image1 + image2
286 [[[1. 1. 1. 1. 0. 0. 0.]
287 [1. 1. 1. 1. 0. 0. 0.]
288 [1. 1. 1. 2. 1. 1. 1.]
289 [0. 0. 0. 1. 1. 1. 1.]
290 [0. 0. 0. 1. 1. 1. 1.]]
292 [[1. 1. 1. 1. 0. 0. 0.]
293 [1. 1. 1. 1. 0. 0. 0.]
294 [1. 1. 1. 2. 1. 1. 1.]
295 [0. 0. 0. 1. 1. 1. 1.]
296 [0. 0. 0. 1. 1. 1. 1.]]]
298 bbox=Box(shape=(5, 7), origin=(0, 0))
300 If instead you want to additively ``insert`` image 1 into image 2,
301 so that they have the same bounding box as image 2, use
303 >>> _ = image2.insert(image1)
314 bbox=Box(shape=(3, 4), origin=(2, 3))
316 To insert an image using a different operation use
318 >>> from operator import truediv
319 >>> _ = image2.insert(image1, truediv)
330 bbox=Box(shape=(3, 4), origin=(2, 3))
333 However, depending on the operation you may get unexpected results
334 since now there could be ``NaN`` and ``inf`` values due to the zeros
335 in the non-overlapping regions.
336 Instead, to select only the overlap region one can use
338 >>> result = image1 / image2
339 >>> print(result[image1.bbox & image2.bbox])
345 bbox=Box(shape=(1, 1), origin=(2, 3))
351 The array data for the image.
353 The bands coving the image.
355 The (y, x) offset for the lower left of the image.
361 bands: Sequence |
None =
None,
362 yx0: tuple[int, int] |
None =
None,
364 if bands
is None or len(bands) == 0:
367 assert len(data.shape) == 2
370 assert len(data.shape) == 3
371 if data.shape[0] != len(bands):
372 raise ValueError(f
"Array has spectral size {data.shape[0]}, but {bands} bands")
380 def from_box(bbox: Box, bands: tuple |
None =
None, dtype: DTypeLike = float) -> Image:
381 """Initialize an empty image from a bounding Box and optional bands
386 The bounding box that contains the image.
388 The bands for the image.
389 If bands is `None` then a 2D image is created.
391 The numpy dtype of the image.
396 An empty image contained in ``bbox`` with ``bands`` bands.
398 if bands
is not None and len(bands) > 0:
399 shape = (len(bands),) + bbox.shape
402 data = np.zeros(shape, dtype=dtype)
403 return Image(data, bands=bands, yx0=cast(tuple[int, int], bbox.origin))
407 """The shape of the image.
409 This includes the spectral dimension, if there is one.
411 return self.
_data.shape
415 """The numpy dtype of the image."""
416 return self.
_data.dtype
420 """The bands used in the image."""
425 """Number of bands in the image.
427 If `n_bands == 0` then the image is 2D and does not have a spectral
434 """Whether or not the image has a spectral dimension."""
439 """Height of the image."""
440 return self.
shape[-2]
444 """Width of the image."""
445 return self.
shape[-1]
448 def yx0(self) -> tuple[int, int]:
449 """Origin of the image, in numpy/C++ y,x ordering."""
454 """location of the y-offset."""
459 """Location of the x-offset."""
464 """Bounding box for the special dimensions in the image."""
469 """The image viewed as a numpy array."""
473 """The indices to extract each band in `bands` in order from the image
475 This converts a band name, or list of band names,
476 into numerical indices that can be used to slice the internal numpy
482 If `bands` is a list of band names, then the result will be an
483 index corresponding to each band, in order.
484 If `bands` is a slice, then the ``start`` and ``stop`` properties
485 should be band names, and the result will be a slice with the
486 appropriate indices to start at `bands.start` and end at
492 Tuple of indices for each band in this image.
494 if isinstance(bands, slice):
497 if bands.start
is None:
501 if bands.stop
is None:
505 return slice(start, stop, bands.step)
507 if isinstance(bands, str):
516 ) -> tuple[tuple[int, ...] | slice, tuple[int, ...] | slice]:
517 """Match bands between two images
522 The other image to match spectral indices to.
527 A tuple with a tuple of indices/slices for each dimension,
528 including the spectral dimension.
532 return slice(
None), slice(
None)
537 err =
"Attempted to insert a monochromatic image into a mutli-band image"
538 raise ValueError(err)
539 if other.n_bands == 0:
540 err =
"Attempted to insert a multi-band image into a monochromatic image"
541 raise ValueError(err)
544 matched_bands = tuple(self.
bandsbands[bidx]
for bidx
in self_indices)
545 other_indices = cast(tuple[int, ...], other.spectral_indices(matched_bands))
546 return other_indices, self_indices
548 def matched_slices(self, bbox: Box) -> tuple[tuple[slice, ...], tuple[slice, ...]]:
549 """Get the slices to match this image to a given bounding box
554 The bounding box to match this image to.
559 Tuple of indices/slices to match this image to the given bbox.
563 _slice = (slice(
None),) * bbox.ndim
564 return _slice, _slice
571 bands: object | tuple[object] |
None =
None,
572 bbox: Box |
None =
None,
574 """Project this image into a different set of bands
579 Spectral bands to project this image into.
580 Not all bands have to be contained in the image, and not all
581 bands contained in the image have to be used in the projection.
583 A bounding box to project the image into.
588 A new image creating by projecting this image into
593 if not isinstance(bands, tuple):
597 data = self.
data[indices, :]
602 return Image(data, bands=bands, yx0=self.
yx0)
605 image = np.zeros((len(bands),) + bbox.shape, dtype=data.dtype)
606 slices = bbox.overlapped_slices(self.
bboxbbox)
608 image[(slice(
None),) + slices[0]] = data[(slice(
None),) + slices[1]]
609 return Image(image, bands=bands, yx0=cast(tuple[int, int], bbox.origin))
611 image = np.zeros(bbox.shape, dtype=data.dtype)
612 slices = bbox.overlapped_slices(self.
bboxbbox)
613 image[slices[0]] = data[slices[1]]
614 return Image(image, bands=bands, yx0=cast(tuple[int, int], bbox.origin))
618 """Return the slices required to slice a multiband image"""
624 op: Callable = operator.add,
626 """Insert this image into another image in place.
631 The image to insert this image into.
633 The operator to use when combining the images.
638 `image` updated by inserting this instance.
642 def insert(self, image: Image, op: Callable = operator.add) -> Image:
643 """Insert another image into this image in place.
648 The image to insert this image into.
650 The operator to use when combining the images.
655 This instance with `image` inserted.
660 """Project a 2D image into the spectral dimension
665 The bands in the projected image.
670 The 2D image repeated in each band in the spectral dimension.
673 raise ValueError(
"Image.repeat only works with 2D images")
675 np.repeat(self.
data[
None, :, :], len(bands), axis=0),
680 def copy(self, order=None) -> Image:
681 """Make a copy of this image.
686 The ordering to use for storing the bytes.
687 This is unlikely to be needed, and just defaults to
688 the numpy behavior (C) ordering.
693 The copy of this image.
699 data: np.ndarray |
None =
None,
700 order: str |
None =
None,
701 bands: tuple[str, ...] |
None =
None,
702 yx0: tuple[int, int] |
None =
None,
704 """Copy of this image with some parameters updated.
706 Any parameters not specified by the user will be copied from the
712 An update for the data in the image.
714 The ordering for stored bytes, from numpy.copy.
716 The bands that the resulting image will have.
717 The number of bands must be the same as the first dimension
720 The lower-left of the image bounding box.
730 data = self.
data.copy(order)
735 return Image(data, bands, yx0)
737 def _i_update(self, op: Callable, other: Image | ScalarLike) -> Image:
738 """Update the data array in place.
740 This is typically implemented by `__i<op>__` methods,
741 like `__iadd__`, to apply an operator and update this image
742 with the data in place.
747 Operator used to combine this image with the `other` image.
749 The other image that is combined with this one using the operator
755 This image, after being updated by the operator
758 if self.
dtype != dtype:
759 if hasattr(other,
"dtype"):
760 _dtype = cast(np.ndarray, other).dtype
763 msg = f
"Cannot update an array with type {self.dtype} with {_dtype}"
764 raise ValueError(msg)
766 self.
_data[:] = result.data
767 self.
_bands = result.bands
768 self.
_yx0 = result.yx0
772 """Compare this array to another.
774 This performs an element by element equality check.
779 The image to compare this image to.
781 The operator used for the comparision (==, !=, >=, <=).
786 An image made by checking all of the elements in this array with
792 If `other` is not an `Image`.
793 MismatchedBandsError:
794 If `other` has different bands.
796 if `other` exists in a different bounding box.
798 if isinstance(other, Image)
and other.bands == self.
bandsbands and other.bbox == self.
bboxbbox:
801 if not isinstance(other, Image):
802 if type(other)
in ScalarTypes:
804 raise TypeError(f
"Cannot compare images to {type(other)}")
807 msg = f
"Cannot compare images with mismatched bands: {self.bands} vs {other.bands}"
811 f
"Cannot compare images with different bounds boxes: {self.bbox} vs. {other.bbox}"
814 def __eq__(self, other: object) -> Image:
815 """Check if this image is equal to another."""
816 if not isinstance(other, Image)
and not isinstance(other, ScalarTypes):
817 raise TypeError(f
"Cannot compare an Image to {type(other)}.")
820 def __ne__(self, other: object) -> Image:
821 """Check if this image is not equal to another."""
822 return ~self.
__eq__(other)
824 def __ge__(self, other: Image | ScalarLike) -> Image:
825 """Check if this image is greater than or equal to another."""
826 if type(other)
in ScalarTypes:
830 def __le__(self, other: Image | ScalarLike) -> Image:
831 """Check if this image is less than or equal to another."""
832 if type(other)
in ScalarTypes:
836 def __gt__(self, other: Image | ScalarLike) -> Image:
837 """Check if this image is greater than or equal to another."""
838 if type(other)
in ScalarTypes:
842 def __lt__(self, other: Image | ScalarLike) -> Image:
843 """Check if this image is less than or equal to another."""
844 if type(other)
in ScalarTypes:
849 """Take the negative of the image."""
853 """Make a copy using of the image."""
857 """Take the inverse (~) of the image."""
860 def __add__(self, other: Image | ScalarLike) -> Image:
861 """Combine this image and another image using addition."""
864 def __iadd__(self, other: Image | ScalarLike) -> Image:
865 """Combine this image and another image using addition and update
870 def __radd__(self, other: Image | ScalarLike) -> Image:
871 """Combine this image and another image using addition,
872 with this image on the right.
874 if type(other)
in ScalarTypes:
876 return cast(Image, other).__add__(self)
878 def __sub__(self, other: Image | ScalarLike) -> Image:
879 """Combine this image and another image using subtraction."""
882 def __isub__(self, other: Image | ScalarLike) -> Image:
883 """Combine this image and another image using subtraction,
884 with this image on the right.
888 def __rsub__(self, other: Image | ScalarLike) -> Image:
889 """Combine this image and another image using subtraction,
890 with this image on the right.
892 if type(other)
in ScalarTypes:
894 return cast(Image, other).__sub__(self)
896 def __mul__(self, other: Image | ScalarLike) -> Image:
897 """Combine this image and another image using multiplication."""
900 def __imul__(self, other: Image | ScalarLike) -> Image:
901 """Combine this image and another image using multiplication,
902 with this image on the right.
906 def __rmul__(self, other: Image | ScalarLike) -> Image:
907 """Combine this image and another image using multiplication,
908 with this image on the right.
910 if type(other)
in ScalarTypes:
912 return cast(Image, other).__mul__(self)
914 def __truediv__(self, other: Image | ScalarLike) -> Image:
915 """Divide this image by `other`."""
919 """Divide this image by `other` in place."""
923 """Divide this image by `other` with this on the right."""
924 if type(other)
in ScalarTypes:
926 return cast(Image, other).__truediv__(self)
928 def __floordiv__(self, other: Image | ScalarLike) -> Image:
929 """Floor divide this image by `other` in place."""
933 """Floor divide this image by `other` in place."""
937 """Floor divide this image by `other` with this on the right."""
938 if type(other)
in ScalarTypes:
940 return cast(Image, other).__floordiv__(self)
942 def __pow__(self, other: Image | ScalarLike) -> Image:
943 """Raise this image to the `other` power."""
946 def __ipow__(self, other: Image | ScalarLike) -> Image:
947 """Raise this image to the `other` power in place."""
950 def __rpow__(self, other: Image | ScalarLike) -> Image:
951 """Raise this other to the power of this image."""
952 if type(other)
in ScalarTypes:
954 return cast(Image, other).__pow__(self)
956 def __mod__(self, other: Image | ScalarLike) -> Image:
957 """Take the modulus of this % other."""
960 def __imod__(self, other: Image | ScalarLike) -> Image:
961 """Take the modulus of this % other in place."""
964 def __rmod__(self, other: Image | ScalarLike) -> Image:
965 """Take the modulus of other % this."""
966 if type(other)
in ScalarTypes:
968 return cast(Image, other).__mod__(self)
970 def __and__(self, other: Image | ScalarLike) -> Image:
971 """Take the bitwise and of this and other."""
974 def __iand__(self, other: Image | ScalarLike) -> Image:
975 """Take the bitwise and of this and other in place."""
978 def __rand__(self, other: Image | ScalarLike) -> Image:
979 """Take the bitwise and of other and this."""
980 if type(other)
in ScalarTypes:
982 return cast(Image, other).__and__(self)
984 def __or__(self, other: Image | ScalarLike) -> Image:
985 """Take the binary or of this or other."""
988 def __ior__(self, other: Image | ScalarLike) -> Image:
989 """Take the binary or of this or other in place."""
992 def __ror__(self, other: Image | ScalarLike) -> Image:
993 """Take the binary or of other or this."""
994 if type(other)
in ScalarTypes:
996 return cast(Image, other).__or__(self)
998 def __xor__(self, other: Image | ScalarLike) -> Image:
999 """Take the binary xor of this xor other."""
1002 def __ixor__(self, other: Image | ScalarLike) -> Image:
1003 """Take the binary xor of this xor other in place."""
1006 def __rxor__(self, other: Image | ScalarLike) -> Image:
1007 """Take the binary xor of other xor this."""
1008 if type(other)
in ScalarTypes:
1010 return cast(Image, other).__xor__(self)
1013 """Shift this image to the left by other bits."""
1014 if not issubclass(np.dtype(type(other)).type, np.integer):
1015 raise TypeError(
"Bit shifting an image can only be done with integers")
1019 """Shift this image to the left by other bits in place."""
1024 """Shift other to the left by this image bits."""
1028 """Shift this image to the right by other bits."""
1029 if not issubclass(np.dtype(type(other)).type, np.integer):
1030 raise TypeError(
"Bit shifting an image can only be done with integers")
1034 """Shift this image to the right by other bits in place."""
1039 """Shift other to the right by this image bits."""
1043 """Display the image array, bands, and bounding box."""
1044 return f
"Image:\n {str(self.data)}\n bands={self.bands}\n bbox={self.bbox}"
1047 """Check to see if an index is a spectral index.
1052 Either a slice, a tuple, or an element in `Image.bands`.
1057 ``True`` if `index` is band or tuple of bands.
1060 if isinstance(index, slice):
1061 if index.start
in bands
or index.stop
in bands
or (index.start
is None and index.stop
is None):
1066 if isinstance(index, tuple)
and index[0]
in self.
bandsbands:
1071 """Get the slices of the image to insert it into the overlapping
1072 region with `bbox`."""
1075 raise IndexError(
"Bounding box is outside of the image")
1076 origin = bbox.origin
1078 y_start = origin[0] - self.
yx0[0]
1079 y_stop = origin[0] + shape[0] - self.
yx0[0]
1080 x_start = origin[1] - self.
yx0[1]
1081 x_stop = origin[1] + shape[1] - self.
yx0[1]
1082 y_index = slice(y_start, y_stop)
1083 x_index = slice(x_start, x_stop)
1084 return y_index, x_index
1086 def _get_sliced(self, indices: Any, value: Image |
None =
None) -> Image:
1087 """Select a subset of an image
1092 The indices to select a subsection of the image.
1093 The spectral index can either be a tuple of indices,
1094 a slice of indices, or a single index used to select a
1095 single-band 2D image.
1096 The spatial index (if present) is a `Box`.
1099 The value used to set this slice of the image.
1100 This allows the single `_get_sliced` method to be used for
1101 both getting a slice of an image and setting it.
1105 result: Image | np.ndarray
1106 The resulting image obtained by selecting subsets of the iamge
1107 based on the `indices`.
1109 if not isinstance(indices, tuple):
1110 indices = (indices,)
1114 if len(indices) > 1
and indices[1]
in self.
bandsbands:
1119 y_index = x_index = slice(
None)
1123 if isinstance(spectral_index, slice):
1125 elif len(spectral_index) == 1:
1127 spectral_index = spectral_index[0]
1129 bands = tuple(self.
bandsbands[idx]
for idx
in spectral_index)
1130 indices = indices[1:]
1131 if len(indices) == 1:
1133 if not isinstance(indices[0], Box):
1134 raise IndexError(f
"Expected a Box for the spatial index but got {indices[1]}")
1136 elif len(indices) == 0:
1137 y_index = x_index = slice(
None)
1139 raise IndexError(f
"Too many spatial indices, expeected a Box bot got {indices}")
1140 full_index = (spectral_index, y_index, x_index)
1141 elif isinstance(indices[0], Box):
1144 full_index = (slice(
None), y_index, x_index)
1146 error = f
"3D images can only be indexed by spectral indices or bounding boxes, got {indices}"
1147 raise IndexError(error)
1149 if len(indices) != 1
or not isinstance(indices[0], Box):
1150 raise IndexError(f
"2D images can only be sliced by bounding box, got {indices}")
1153 full_index = (y_index, x_index)
1166 yx0 = (y0 + self.
yx0[0], x0 + self.
yx0[1])
1168 data = self.
data[full_index]
1170 if len(data.shape) == 2:
1172 return Image(data, yx0=yx0)
1173 return Image(data, bands=bands, yx0=yx0)
1176 self.
_data[full_index] = value.data
1180 """Get the slices needed to insert this image into a bounding box.
1185 The region to insert this image into.
1190 The slice of this image and the slice of the `bbox` required to
1191 insert the overlapping portion of this image.
1196 overlap = (slice(
None),) + overlap[0], (slice(
None),) + overlap[1]
1200 """Get the subset of an image
1205 The indices to select a subsection of the image.
1210 The resulting image obtained by selecting subsets of the iamge
1211 based on the `indices`.
1216 """Set a subset of an image to a given value
1221 The indices to select a subsection of the image.
1223 The value to use for the subset of the image.
1228 The resulting image obtained by selecting subsets of the image
1229 based on the `indices`.
1235 """Perform an operation on two images, that may or may not be spectrally
1236 and spatially aligned.
1241 The image on the LHS of the operation
1243 The image on the RHS of the operation
1245 The operation used to combine the images.
1250 The resulting combined image.
1252 if type(image2)
in ScalarTypes:
1253 return image1.copy_with(data=op(image1.data, image2))
1254 image2 = cast(Image, image2)
1255 if image1.bands == image2.bands
and image1.bbox == image2.bbox:
1257 with np.errstate(divide=
"ignore", invalid=
"ignore"):
1258 result = op(image1.data, image2.data)
1259 return Image(result, bands=image1.bands, yx0=image1.yx0)
1261 if op != operator.add
and op != operator.sub
and image1.bands != image2.bands:
1262 msg =
"Images with different bands can only be combined using addition and subtraction, "
1263 msg += f
"got {op}, with bands {image1.bands}, {image2.bands}"
1264 raise ValueError(msg)
1267 bands = image1.bands
1269 bands = bands + tuple(band
for band
in image2.bands
if band
not in bands)
1271 bbox = image1.bbox | image2.bbox
1274 shape = (len(bands),) + bbox.shape
1278 if op == operator.add
or op == operator.sub:
1280 result =
Image(np.zeros(shape, dtype=dtype), bands=bands, yx0=cast(tuple[int, int], bbox.origin))
1282 image1.insert_into(result, operator.add)
1284 image2.insert_into(result, op)
1287 image1 = image1.project(bbox=bbox)
1288 image2 = image2.project(bbox=bbox)
1289 result = op(image1, image2)
1296 op: Callable = operator.add,
1298 """Insert one image into another image
1303 The image that will have `sub_image` insertd.
1305 The image that is inserted into `main_image`.
1307 The operator to use for insertion
1308 (addition, subtraction, multiplication, etc.).
1313 The `main_image`, with the `sub_image` inserted in place.
1315 if len(main_image.bands) == 0
and len(sub_image.bands) == 0:
1316 slices = sub_image.matched_slices(main_image.bbox)
1317 image_slices = slices[1]
1318 self_slices = slices[0]
1320 band_indices = sub_image.matched_spectral_indices(main_image)
1321 slices = sub_image.matched_slices(main_image.bbox)
1322 image_slices = (band_indices[0],) + slices[1]
1323 self_slices = (band_indices[1],) + slices[0]
1325 main_image._data[image_slices] = op(main_image.data[image_slices], sub_image.data[self_slices])
copy_with(self, np.ndarray|None data=None, str|None order=None, tuple[str,...]|None bands=None, tuple[int, int]|None yx0=None)
Image __or__(self, Image|ScalarLike other)
Image _i_update(self, Callable op, Image|ScalarLike other)
Image __sub__(self, Image|ScalarLike other)
tuple[tuple[int,...]|slice, slice, slice] multiband_slices(self)
Image __rlshift__(self, ScalarLike other)
Image __ne__(self, object other)
Image __rand__(self, Image|ScalarLike other)
Image _check_equality(self, Image|ScalarLike other, Callable op)
Image __rtruediv__(self, Image|ScalarLike other)
tuple[int, int] yx0(self)
__init__(self, np.ndarray data, Sequence|None bands=None, tuple[int, int]|None yx0=None)
Image __and__(self, Image|ScalarLike other)
tuple[tuple[int,...]|slice, tuple[int,...]|slice] matched_spectral_indices(self, Image other)
Image __ilshift__(self, ScalarLike other)
Image __iadd__(self, Image|ScalarLike other)
Image __eq__(self, object other)
Image __rmul__(self, Image|ScalarLike other)
bool _is_spectral_index(self, Any index)
Image __itruediv__(self, Image|ScalarLike other)
Image copy(self, order=None)
Image __ipow__(self, Image|ScalarLike other)
Image __iand__(self, Image|ScalarLike other)
Image __lt__(self, Image|ScalarLike other)
Image __setitem__(self, indices, Image value)
Image __imod__(self, Image|ScalarLike other)
tuple[slice, slice] _get_box_slices(self, Box bbox)
Image __ge__(self, Image|ScalarLike other)
Image __pow__(self, Image|ScalarLike other)
Image __mod__(self, Image|ScalarLike other)
tuple[tuple[slice,...], tuple[slice,...]] overlapped_slices(self, Box bbox)
Image __gt__(self, Image|ScalarLike other)
tuple[int,...] shape(self)
Image __floordiv__(self, Image|ScalarLike other)
Image __rpow__(self, Image|ScalarLike other)
tuple[tuple[slice,...], tuple[slice,...]] matched_slices(self, Box bbox)
Image __rfloordiv__(self, Image|ScalarLike other)
Image __truediv__(self, Image|ScalarLike other)
Image __xor__(self, Image|ScalarLike other)
Image insert(self, Image image, Callable op=operator.add)
Image insert_into(self, Image image, Callable op=operator.add)
Image __imul__(self, Image|ScalarLike other)
Image __rsub__(self, Image|ScalarLike other)
Image __getitem__(self, Any indices)
Image __ror__(self, Image|ScalarLike other)
Image __lshift__(self, ScalarLike other)
Image from_box(Box bbox, tuple|None bands=None, DTypeLike dtype=float)
Image _get_sliced(self, Any indices, Image|None value=None)
Image __ixor__(self, Image|ScalarLike other)
tuple[int,...]|slice spectral_indices(self, Sequence|slice bands)
Image __rrshift__(self, ScalarLike other)
Image project(self, object|tuple[object]|None bands=None, Box|None bbox=None)
Image __rxor__(self, Image|ScalarLike other)
Image __mul__(self, Image|ScalarLike other)
Image __le__(self, Image|ScalarLike other)
Image __isub__(self, Image|ScalarLike other)
Image __irshift__(self, ScalarLike other)
Image repeat(self, tuple bands)
Image __rmod__(self, Image|ScalarLike other)
Image __rshift__(self, ScalarLike other)
Image __add__(self, Image|ScalarLike other)
Image __radd__(self, Image|ScalarLike other)
Image __ifloordiv__(self, Image|ScalarLike other)
Image __ior__(self, Image|ScalarLike other)
Image _operate_on_images(Image image1, Image|ScalarLike image2, Callable op)
list[DTypeLike] get_dtypes(*np.ndarray|Image|ScalarLike data)
DTypeLike get_combined_dtype(*np.ndarray|Image|ScalarLike data)
Image insert_image(Image main_image, Image sub_image, Callable op=operator.add)