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