lsst.afw  16.0-12-gf08c31002
slicing.py
Go to the documentation of this file.
1 from lsst.geom import Point2I, Box2I
2 from .image import LOCAL, PARENT, ImageOrigin
3 
4 __all__ = ["supportSlicing"]
5 
6 
7 def splitSliceArgs(sliceArgs):
8  """Separate the actual slice from origin arguments to __getitem__ or
9  __setitem__, using PARENT for the origin if it is not provided.
10 
11  Parameter
12  ---------
13  sliceArgs : `tuple`, `Box2I`, or `Point2I`
14  The first argument passed to an image-like object's
15  ``__getitem__`` or ``__setitem__``.
16 
17  Returns
18  -------
19  sliceArgs : `tuple`, `Box2I`, or `Point2I`
20  The original sliceArgs passed in, with any ImageOrigin argument
21  stripped off.
22  origin : `ImageOrigin`
23  Enum value that sets whether or not to consider xy0 in positions.
24 
25  See interpretSliceArgs for more information.
26 
27  Intended primarily for internal use by `supportSlicing()`.
28  """
29  defaultOrigin = PARENT
30  try:
31  if isinstance(sliceArgs[-1], ImageOrigin):
32  # Args are already a tuple that includes the origin.
33  if len(sliceArgs) == 2:
34  return sliceArgs[0], sliceArgs[-1]
35  else:
36  return sliceArgs[:-1], sliceArgs[-1]
37  else:
38  # Args are a tuple that does not include the origin; add it to make origin explicit.
39  return sliceArgs, defaultOrigin
40  except TypeError: # Arg is a scalar; return it along with the default origin.
41  return sliceArgs, defaultOrigin
42 
43 
44 def handleNegativeIndex(index, size, origin, default):
45  """Handle negative indices passed to image accessors.
46 
47  When negative indices are used in LOCAL coordinates, we interpret them as
48  relative to the upper bounds of the array, as in regular negative indexing
49  in Python.
50 
51  Using negative indices in PARENT coordinates is not allowed unless passed
52  via a `Point2I` or `Box2I`; the potential for confusion between actual
53  negative indices (when ``xy0 < 0``) and offsets relative to the upper
54  bounds of the array is too great.
55 
56  Parameters
57  ----------
58  index : `int` or `None`
59  1-d pixel index to interpret, as given by a caller to an image-like
60  object's ``__getitem__`` or ``__setitem__``.
61  size : `int`
62  Size of the image in the dimension corresponding to ``index``.
63  origin : `ImageOrigin`
64  Enum value that sets whether or not to consider xy0 in positions.
65  default : `int`
66  Index to return if `index` is None.
67 
68  Returns
69  -------
70  index : `int`
71  If ``origin==PARENT``, either the given ``index`` or ``default``.
72  If ``origin==LOCAL``, an equivalent index guaranteed to be nonnegative.
73 
74  Intended primarily for internal use by `supportSlicing()`.
75  """
76  if index is None:
77  assert default is not None
78  return default
79  if index < 0:
80  if origin == LOCAL:
81  index = size + index
82  else:
83  raise IndexError("Negative indices are not permitted with the PARENT origin. "
84  "Use LOCAL to use negative to index relative to the end, "
85  "and Point2I or Box2I indexing to access negative pixels "
86  "in PARENT coordinates.")
87  return index
88 
89 
90 def makePointFromIndices(x, y, origin, bbox):
91  """Create a Point2I from an x, y pair, correctly handling negative indices.
92 
93  Parameters
94  ----------
95  x : `int`
96  Column index.
97  y : `int`
98  Row index.
99  origin : `ImageOrigin`
100  Enum value that sets whether or not to consider xy0 in positions.
101  bbox : `Box2I`
102  Bounding box of the image being indexed, obtained using
103  ``getBBox(origin)``.
104 
105  Returns
106  -------
107  point : `Point2I`
108  A point corresponding to the given indices.
109 
110  Intended primarily for internal use by `supportSlicing()`.
111  """
112  return Point2I(
113  handleNegativeIndex(x, bbox.getWidth(), origin, default=None),
114  handleNegativeIndex(y, bbox.getHeight(), origin, default=None)
115  )
116 
117 
118 def makeBoxFromSlices(x, y, origin, bbox):
119  """Transform a tuple of slice objects into a Box2I, correctly handling negative indices.
120 
121  Parameters
122  ----------
123  x : `slice`
124  Column index range. Step must be None.
125  y : `slice`
126  Row index range. Step must be None.
127  origin : `ImageOrigin`
128  Enum value that sets whether or not to consider xy0 in positions.
129  bbox : `Box2I`
130  Bounding box of the image being indexed, obtained using
131  ``getBBox(origin)``.
132 
133  Returns
134  -------
135  bbox : `Box2I`
136  A point corresponding to the given indices.
137 
138  Intended primarily for internal use by `supportSlicing()`.
139  """
140  if x.step is not None or y.step is not None:
141  raise ValueError("Slices with steps are not supported in image indexing.")
142  begin = Point2I(
143  handleNegativeIndex(x.start, bbox.getWidth(), origin, default=bbox.getBeginX()),
144  handleNegativeIndex(y.start, bbox.getHeight(), origin, default=bbox.getBeginY())
145  )
146  end = Point2I(
147  handleNegativeIndex(x.stop, bbox.getWidth(), origin, default=bbox.getEndX()),
148  handleNegativeIndex(y.stop, bbox.getHeight(), origin, default=bbox.getEndY())
149  )
150  return Box2I(begin, end - begin)
151 
152 
153 def interpretSliceArgs(sliceArgs, bboxGetter):
154  """Transform arguments to __getitem__ or __setitem__ to a standard form.
155 
156  Parameters
157  ----------
158  sliceArgs : `tuple`, `Box2I`, or `Point2I`
159  Slice arguments passed directly to `__getitem__` or `__setitem__`.
160  bboxGetter : callable
161  Callable that accepts an ImageOrigin enum value and returns the
162  appropriate image bounding box. Usually the bound getBBox method
163  of an Image, Mask, or MaskedImage object.
164 
165  Returns
166  -------
167  box : `Box2I` or `None`
168  A box to use to create a subimage, or None if the slice refers to a
169  scalar.
170  index: `tuple` or `None`
171  An ``(x, y)`` tuple of integers, or None if the slice refers to a
172  box.
173  origin : `ImageOrigin`
174  Enum indicating whether to account for xy0.
175 
176  Intended primarily for internal use by `supportSlicing()`.
177  """
178  slices, origin = splitSliceArgs(sliceArgs)
179  if isinstance(slices, Point2I):
180  return None, slices, origin
181  elif isinstance(slices, Box2I):
182  return slices, None, origin
183  elif isinstance(slices, slice):
184  if slices.start is not None or slices.stop is not None or slices.step is not None:
185  raise TypeError("Single-dimension slices must not have bounds.")
186  x = slices
187  y = slices
188  origin = LOCAL # doesn't matter, as the slices cover the full image
189  else:
190  x, y = slices
191  if isinstance(x, slice):
192  if isinstance(y, slice):
193  return makeBoxFromSlices(x, y, origin=origin, bbox=bboxGetter(origin)), None, origin
194  raise TypeError("Mixed indices of the form (slice, int) are not supported for images.")
195  else:
196  if isinstance(y, slice):
197  raise TypeError("Mixed indices of the form (int, slice) are not supported for images.")
198  return None, makePointFromIndices(x, y, origin=origin, bbox=bboxGetter(origin)), origin
199 
200 
201 def supportSlicing(cls):
202  """Support image slicing
203  """
204 
205  def Factory(self, *args, **kwargs):
206  """Return an object of this type
207  """
208  return cls(*args, **kwargs)
209  cls.Factory = Factory
210 
211  def clone(self):
212  """Return a deep copy of self"""
213  return cls(self, True)
214  cls.clone = clone
215 
216  def __getitem__(self, imageSlice):
217  box, index, origin = interpretSliceArgs(imageSlice, self.getBBox)
218  if box is not None:
219  return self.subset(box, origin=origin)
220  return self._get(index, origin=origin)
221  cls.__getitem__ = __getitem__
222 
223  def __setitem__(self, imageSlice, rhs):
224  box, index, origin = interpretSliceArgs(imageSlice, self.getBBox)
225  if box is not None:
226  if self.assign(rhs, box, origin) is NotImplemented:
227  lhs = self.subset(box, origin=origin)
228  lhs.set(rhs)
229  else:
230  self._set(index, origin=origin, value=rhs)
231  cls.__setitem__ = __setitem__
def makePointFromIndices(x, y, origin, bbox)
Definition: slicing.py:90
def interpretSliceArgs(sliceArgs, bboxGetter)
Definition: slicing.py:153
def splitSliceArgs(sliceArgs)
Definition: slicing.py:7
def makeBoxFromSlices(x, y, origin, bbox)
Definition: slicing.py:118
def handleNegativeIndex(index, size, origin, default)
Definition: slicing.py:44