lsst.afw  14.0-25-g0e8fc950e+7
slicing.py
Go to the documentation of this file.
1 from __future__ import absolute_import, division, print_function
2 
3 import lsst.afw.geom as afwGeom
4 from .image import LOCAL, PARENT, ImageOrigin
5 
6 __all__ = ["supportSlicing"]
7 
8 
9 def _getBBoxFromSliceTuple(img, imageSlice):
10  """Given a slice specification return the proper Box2I and origin
11  This is the worker routine behind __getitem__ and __setitem__
12 
13  The imageSlice may be:
14  lsst.afw.geom.Box2I
15  slice, slice
16  :
17  Only the first one or two parts of the slice are recognised (no stride), a single int is
18  interpreted as n:n+1, and negative indices are interpreted relative to the end of the array,
19  so supported slices include:
20  2
21  -1
22  1:10
23  :-2
24  : (equivalent to ... (python's Ellipsis) which is also supported)
25 
26  E.g.
27  im[-1, :]
28  im[..., 18]
29  im[4, 10]
30  im[-3:, -2:]
31  im[-2, -2]
32  im[1:4, 6:10]
33  im[:]
34 
35  You may also add an extra argument, afwImage.PARENT or afwImage.LOCAL. The default is LOCAL
36  as before, but if you specify PARENT the bounding box is interpreted in PARENT coordinates
37  (this includes slices; e.g.
38  im[-3:, -2:, afwImage.PARENT]
39  still means the last few rows and columns, and
40  im[1001:1004, 2006:2010, afwImage.PARENT]
41  with xy0 = (1000, 2000) refers to the same pixels as
42  im[1:4, 6:10, afwImage.LOCAL]
43  )
44  """
45  origin = LOCAL # this sets the default value
46 
47  try:
48  _origin = imageSlice[-1]
49  except TypeError:
50  _origin = None
51 
52  if isinstance(_origin, ImageOrigin):
53  origin = _origin
54  imageSlice = imageSlice[0] if len(imageSlice) <= 2 else imageSlice[:-1]
55 
56  if isinstance(imageSlice, afwGeom.Box2I):
57  return imageSlice, origin
58 
59  if isinstance(imageSlice, slice) and imageSlice.start is None and imageSlice.stop is None:
60  imageSlice = (Ellipsis, Ellipsis,)
61 
62  if not (isinstance(imageSlice, tuple) and len(imageSlice) == 2 and
63  sum([isinstance(_, (slice, type(Ellipsis), int)) for _ in imageSlice]) == 2):
64  raise IndexError(
65  "Images may only be indexed as a 2-D slice not %s" % imageSlice)
66 
67  # Because we're going to use slice.indices(...) to construct our ranges, and
68  # python doesn't understand PARENT coordinate systems, we need
69  # to convert slices specified in PARENT coords to LOCAL
70 
71  imageSlice, _imageSlice = [], imageSlice
72  for s, wh, z0 in zip(_imageSlice, img.getDimensions(), img.getXY0()):
73  if origin == LOCAL:
74  z0 = 0 # ignore image's xy0
75 
76  if isinstance(s, slice):
77  if z0 != 0:
78  start = s.start if s.start is None or s.start < 0 else s.start - z0
79  stop = s.stop if s.stop is None or s.stop < 0 else s.stop - z0
80  s = slice(start, stop, s.step)
81  elif isinstance(s, int):
82  if s < 0:
83  s += z0 + wh
84  s = slice(s - z0, s - z0 + 1)
85  else:
86  s = slice(0, wh)
87 
88  imageSlice.append(s)
89 
90  x, y = [_.indices(wh) for _, wh in zip(imageSlice, img.getDimensions())]
91  return afwGeom.Box2I(afwGeom.Point2I(x[0], y[0]), afwGeom.Point2I(x[1] - 1, y[1] - 1)), LOCAL
92 
93 def supportSlicing(cls):
94  """Support image slicing
95  """
96 
97  def _checkOrigin(origin):
98  if origin not in (LOCAL, PARENT):
99  raise RuntimeError("keyword origin must be afwImage.ORIGIN or afwImage.PARENT, not %s" % origin)
100 
101  def Factory(self, *args, **kwargs):
102  """Return an object of this type
103  """
104  return cls(*args, **kwargs)
105  cls.Factory = Factory
106 
107  def clone(self):
108  """Return a deep copy of self"""
109  return cls(self, True)
110  cls.clone = clone
111 
112  def __getitem__(self, imageSlice):
113  bbox, origin = _getBBoxFromSliceTuple(self, imageSlice)
114 
115  _checkOrigin(origin)
116  return self.Factory(self, bbox, origin)
117  cls.__getitem__ = __getitem__
118 
119  def __setitem__(self, imageSlice, rhs):
120  bbox, origin = _getBBoxFromSliceTuple(self, imageSlice)
121 
122  _checkOrigin(origin)
123  if self.assign(rhs, bbox, origin) is NotImplemented:
124  lhs = self.Factory(self, bbox, origin=origin)
125  lhs.set(rhs)
126  cls.__setitem__ = __setitem__
127 
128  def __float__(self):
129  """Convert a 1x1 image to a floating scalar"""
130  if self.getDimensions() != afwGeom.Extent2I(1, 1):
131  raise TypeError(
132  "Only single-pixel images may be converted to python scalars")
133 
134  try:
135  return float(self.get(0, 0))
136  except AttributeError:
137  raise TypeError(
138  "Unable to extract a single pixel from a {}".format(type(self).__name__))
139  except TypeError:
140  raise TypeError(
141  "Unable to convert a {} pixel to a scalar".format(type(self).__name__))
142  cls.__float__ = __float__
143 
144  def __int__(self):
145  """Convert a 1x1 image to a integral scalar"""
146  return int(float(self))
147  cls.__int__ = __int__
An integer coordinate rectangle.
Definition: Box.h:55
def supportSlicing(cls)
Definition: slicing.py:93