1 from __future__
import absolute_import, division, print_function
2 from builtins
import range
3 from builtins
import object
37 logger = lsst.log.Log.getLogger(
"afw.display.interface")
40 "WHITE",
"BLACK",
"RED",
"GREEN",
"BLUE",
"CYAN",
"MAGENTA",
"YELLOW",
"ORANGE",
41 "Display",
"Event",
"noop_callback",
"h_callback",
42 "setDefaultBackend",
"getDefaultBackend",
43 "setDefaultFrame",
"getDefaultFrame",
"incrDefaultFrame",
44 "setDefaultMaskTransparency",
"setDefaultMaskPlaneColor",
45 "getDisplay",
"delAllDisplays",
62 def _makeDisplayImpl(display, backend, *args, **kwargs):
63 """!Return the DisplayImpl for the named backend
65 \param display Name of device. Should be importable, either absolutely or relative to lsst.display
66 \param backend The desired backend
67 \param args Arguments passed to DisplayImpl.__init__
68 \param kwargs Keywords arguments passed to DisplayImpl.__init__
71 import lsst.afw.display as afwDisplay
72 display = afwDisplay.Display(display=1, backend="ds9")
74 _makeDisplayImpl(..., "ds9", 1)
75 and import the ds9 implementation of DisplayImpl from lsst.display.ds9
79 for dt
in (
"lsst.display.%s" % backend, backend,
".%s" % backend,
"lsst.afw.display.%s" % backend):
83 if dt.startswith(
"."):
84 impargs[
"package"] =
"lsst.display"
86 _disp = importlib.import_module(dt, **impargs)
88 except (ImportError, SystemError)
as e:
94 if not _disp
or not hasattr(_disp.DisplayImpl,
"_show"):
100 "Could not load the requested backend: {}".format(backend))
103 _impl = _disp.DisplayImpl(display, *args, **kwargs)
104 if not hasattr(_impl,
"frame"):
105 _impl.frame = display.frame
114 _defaultBackend =
None
116 _defaultMaskPlaneColor = dict(
123 DETECTED_NEGATIVE=CYAN,
130 _defaultMaskTransparency = {}
132 def __init__(self, frame=None, backend=None, *args, **kwargs):
133 """!Create an object able to display images and overplot glyphs
135 \param frame An identifier for the display
136 \param backend The backend to use (defaults to value set by setDefaultBackend())
137 \param args Arguments to pass to the backend
138 \param kwargs Arguments to pass to the backend
144 if Display._defaultBackend
is None:
150 backend = Display._defaultBackend
153 self.
_impl = _makeDisplayImpl(self, backend, *args, **kwargs)
163 for ik
in range(ord(
'a'), ord(
'z') + 1):
168 for k
in (
'Return',
'Shift_L',
'Shift_R'):
171 for k
in (
'q',
'Escape'):
174 def _h_callback(k, x, y):
177 for k
in sorted(self._callbacks.keys()):
179 print(
" %-6s %s" % (k, doc.split(
"\n")[0]
if doc
else "???"))
183 Display._displays[frame] = self
186 """!Support for python's with statement"""
190 """!Support for python's with statement"""
197 """Try to call self._impl.name(*args, *kwargs)"""
199 if not (hasattr(self,
"_impl")
and self.
_impl):
200 raise AttributeError(
"Device has no _impl attached")
203 return getattr(self.
_impl, name)
204 except AttributeError:
205 raise AttributeError(
206 "Device %s has no attribute \"%s\"" % (self.
name, name))
209 if hasattr(self,
"_impl")
and self.
_impl:
213 if self.
frame in Display._displays:
214 del Display._displays[self.
frame]
218 """!The backend's verbosity"""
219 return self._impl.verbose
224 self._impl.verbose = value
227 return "Display[%s]" % (self.
frame)
235 _makeDisplayImpl(
None, backend)
236 except Exception
as e:
238 "Unable to set backend to %s: \"%s\"" % (backend, e))
240 Display._defaultBackend = backend
244 return Display._defaultBackend
248 """Set the default frame for display"""
249 Display._defaultFrame = frame
253 """Get the default frame for display"""
254 return Display._defaultFrame
258 """Increment the default frame for display"""
259 Display._defaultFrame += 1
260 return Display._defaultFrame
264 if hasattr(maskPlaneTransparency,
"copy"):
265 maskPlaneTransparency = maskPlaneTransparency.copy()
267 Display._defaultMaskTransparency = maskPlaneTransparency
271 """!Set the default mapping from mask plane names to colours
272 \param name name of mask plane, or a dict mapping names to colours
273 \param color Desired color, or None if name is a dict
275 If name is None, use the hard-coded default dictionary
279 name = Display._defaultMaskPlaneColor
281 if isinstance(name, dict):
283 for k, v
in name.items():
289 Display._defaultMaskPlaneColor[name] = color
292 def getDisplay(frame=None, backend=None, create=True, verbose=False, *args, **kwargs):
293 """!Return the Display indexed by frame, creating it if needs be
295 \param frame The desired frame (None => use defaultFrame (see setDefaultFrame))
296 \param backend create the specified frame using this backend (or the default if None) \
297 if it doesn't already exist. If backend == "", it's an error to specify a non-existent frame
298 \param create create the display if it doesn't already exist.
299 \param verbose Allow backend to be chatty
300 \param args arguments passed to Display constructor
301 \param kwargs keyword arguments passed to Display constructor
305 frame = Display._defaultFrame
307 if frame
not in Display._displays:
309 raise RuntimeError(
"Frame %s does not exist" % frame)
311 Display._displays[frame] =
Display(
312 frame, backend, verbose=verbose, *args, **kwargs)
314 Display._displays[frame].verbose = verbose
315 return Display._displays[frame]
319 """!Delete and close all known display
321 for disp
in list(Display._displays.values()):
323 Display._displays = {}
326 """!A generator for "standard" colours
328 \param omitBW Don't include Black and White
331 colorGenerator = interface.maskColorGenerator(omitBW=True)
333 print p, next(colorGenerator)
335 _maskColors = [WHITE, BLACK, RED, GREEN,
336 BLUE, CYAN, MAGENTA, YELLOW, ORANGE]
341 color = _maskColors[i%len(_maskColors)]
342 if omitBW
and color
in (BLACK, WHITE):
348 """!Request that mask plane name be displayed as color
350 \param name Name of mask plane or a dictionary of name -> colourName
351 \param color The name of the colour to use (must be None if name is a dict)
353 Colours may be specified as any X11-compliant string (e.g. <tt>"orchid"</tt>), or by one
354 of the following constants defined in \c afwDisplay: \c BLACK, \c WHITE, \c RED, \c BLUE,
355 \c GREEN, \c CYAN, \c MAGENTA, \c YELLOW.
357 The advantage of using the symbolic names is that the python interpreter can detect typos.
361 if isinstance(name, dict):
363 for k, v
in name.items():
370 """!Return the colour associated with the specified mask plane name"""
372 return self._maskPlaneColors.get(name)
375 """!Specify display's mask transparency (percent); or None to not set it when loading masks"""
377 if isinstance(transparency, dict):
379 for k, v
in transparency.items():
383 if transparency
is not None and (transparency < 0
or transparency > 100):
385 "Mask transparency should be in the range [0, 100]; clipping", file=sys.stderr)
391 if transparency
is not None:
392 self._impl._setMaskTransparency(transparency, name)
395 """!Return the current display's mask transparency"""
397 return self._impl._getMaskTransparency(name)
400 """!Uniconify and Raise display. N.b. throws an exception if frame doesn't exit"""
401 return self._impl._show()
403 def mtv(self, data, title="", wcs=None):
404 """!Display an Image or Mask on a DISPLAY display
406 Historical note: the name "mtv" comes from Jim Gunn's forth imageprocessing
407 system, Mirella (named after Mirella Freni); The "m" stands for Mirella.
409 if hasattr(data,
"getXY0"):
410 self.
_xy0 = data.getXY0()
418 "You may not specify a wcs with an Exposure")
419 data, wcs = data.getMaskedImage(), data.getWcs()
422 self.
_xy0 = data.getXY0()
425 self._impl._mtv(data,
None, wcs, title)
432 self._impl._mtv(afwImage.ImageU(data.getArray()), data, wcs, title)
435 self._impl._mtv(data.getImage(), data.getMask(), wcs, title)
437 raise RuntimeError(
"Unsupported type %s" % repr(data))
443 """A class intended to be used with python's with statement"""
449 self._impl._buffer(
True)
452 self._impl._buffer(
False)
456 """Return a class intended to be used with python's with statement
458 with display.Buffering():
459 display.dot("+", xc, yc)
464 """!Flush the buffers"""
468 """!Erase the specified DISPLAY frame
472 def dot(self, symb, c, r, size=2, ctype=None, origin=afwImage.PARENT, *args, **kwargs):
473 """!Draw a symbol onto the specified DISPLAY frame at (col,row) = (c,r)
474 [0-based coordinates]
481 @:Mxx,Mxy,Myy Draw an ellipse with moments (Mxx, Mxy, Myy) (argument size is ignored)
482 An object derived from afwGeom.ellipses.BaseCore Draw the ellipse (argument size is ignored)
483 Any other value is interpreted as a string to be drawn. Strings obey the fontFamily (which may be
484 extended with other characteristics, e.g. "times bold italic". Text will be drawn rotated by
485 textAngle (textAngle is ignored otherwise).
487 N.b. objects derived from BaseCore include Axes and Quadrupole.
489 if isinstance(symb, int):
492 if origin == afwImage.PARENT
and self.
_xy0 is not None:
497 if isinstance(symb, afwGeom.ellipses.BaseCore)
or re.search(
r"^@:", symb):
499 mat = re.search(
r"^@:([^,]+),([^,]+),([^,]+)", symb)
504 mxx, mxy, myy = [float(_)
for _
in mat.groups()]
505 symb = afwGeom.ellipses.Quadrupole(mxx, myy, mxy)
507 symb = afwGeom.ellipses.Axes(symb)
509 self._impl._dot(symb, c, r, size, ctype, **kwargs)
511 def line(self, points, origin=afwImage.PARENT, symbs=False, ctype=None, size=0.5):
512 """!Draw a set of symbols or connect the points, a list of (col,row)
513 If symbs is True, draw points at the specified points using the desired symbol,
514 otherwise connect the dots. Ctype is the name of a colour (e.g. 'red')
516 If symbs supports indexing (which includes a string -- caveat emptor) the
517 elements are used to label the points
523 symbs = len(points)*list(symbs)
525 for i, xy
in enumerate(points):
526 self.
dot(symbs[i], *xy, size=size, ctype=ctype)
529 if origin == afwImage.PARENT
and self.
_xy0 is not None:
531 _points = list(points)
532 for i, p
in enumerate(points):
533 _points[i] = (p[0] - x0, p[1] - y0)
536 self._impl._drawLines(points, ctype)
541 def scale(self, algorithm, min, max=None, unit=None, *args, **kwargs):
542 """!Set the range of the scaling from DN in the image to the image display
543 \param algorithm Desired scaling (e.g. "linear" or "asinh")
544 \param min Minimum value, or "minmax" or "zscale"
545 \param max Maximum value (must be None for minmax|zscale)
546 \param unit Units for min and max (e.g. Percent, Absolute, Sigma; None if min==minmax|zscale)
547 \param *args Optional arguments
548 \param **kwargs Optional keyword arguments
550 if min
in (
"minmax",
"zscale"):
551 assert max
is None,
"You may not specify \"%s\" and max" % min
552 assert unit
is None,
"You may not specify \"%s\" and unit" % min
554 raise RuntimeError(
"Please specify max")
556 self._impl._scale(algorithm, min, max, unit, *args, **kwargs)
561 def zoom(self, zoomfac=None, colc=None, rowc=None, origin=afwImage.PARENT):
562 """!Zoom frame by specified amount, optionally panning also"""
564 if (rowc
and colc
is None)
or (colc
and rowc
is None):
566 "Please specify row and column center to pan about")
569 if origin == afwImage.PARENT
and self.
_xy0 is not None:
574 self._impl._pan(colc, rowc)
576 if zoomfac
is None and rowc
is None:
579 if zoomfac
is not None:
580 self._impl._zoom(zoomfac)
582 def pan(self, colc=None, rowc=None, origin=afwImage.PARENT):
583 """!Pan to (rowc, colc); see also zoom"""
585 self.
zoom(
None, colc, rowc, origin)
588 """!Enter an interactive loop, listening for key presses in display and firing callbacks.
589 Exit with q, \c CR, \c ESC, or any other callback function that returns a ``True`` value.
591 interactFinished =
False
593 while not interactFinished:
594 ev = self._impl._getEvent()
597 k, x, y = ev.k, ev.x, ev.y
600 logger.warn(
"No callback registered for {0}".format(k))
603 interactFinished = self.
_callbacks[k](k, x, y)
604 except Exception
as e:
606 "Display._callbacks[{0}]({0},{1},{2}) failed: {3}".format(k, x, y, e))
609 """!Set the callback for key k to be func, returning the old callback
616 "Key '%s' is already in use by display, so I can't add a callback for it" % k)
618 ofunc = self._callbacks.get(k)
619 self.
_callbacks[k] = func
if func
else noop_callback
621 self._impl._setCallback(k, self.
_callbacks[k])
626 """!Return all callback keys
627 \param onlyActive If true only return keys that do something
630 return sorted([k
for k, func
in self._callbacks.items()
if
631 not (onlyActive
and func == noop_callback)])
639 """!A class to handle events such as key presses in image display windows"""
641 def __init__(self, k, x=float(
'nan'), y=float(
'nan')):
647 return "%s (%.2f, %.2f)" % (self.
k, self.
x, self.
y)
654 """!Callback function: arguments key, x, y"""
659 print(
"Enter q or <ESC> to leave interactive mode, h for this help, or a letter to fire a callback")
670 Display.setDefaultBackend(backend)
674 return Display.getDefaultBackend()
678 return Display.setDefaultFrame(frame)
682 """Get the default frame for display"""
683 return Display.getDefaultFrame()
687 """Increment the default frame for display"""
688 return Display.incrDefaultFrame()
692 return Display.setDefaultMaskTransparency(maskPlaneTransparency)
696 """!Set the default mapping from mask plane names to colours
697 \param name name of mask plane, or a dict mapping names to colours
698 \param color Desired color, or None if name is a dict
700 If name is None, use the hard-coded default dictionary
703 return Display.setDefaultMaskPlaneColor(name, color)
706 def getDisplay(frame=None, backend=None, create=True, verbose=False, *args, **kwargs):
707 """!Return the Display indexed by frame, creating it if needs be
709 See Display.getDisplay
711 \param frame The desired frame (None => use defaultFrame (see setDefaultFrame))
712 \param backend create the specified frame using this backend (or the default if None) \
713 if it doesn't already exist. If backend == "", it's an error to specify a non-existent frame
714 \param create create the display if it doesn't already exist.
715 \param verbose Allow backend to be chatty
716 \param args arguments passed to Display constructor
717 \param kwargs keyword arguments passed to Display constructor
720 return Display.getDisplay(frame, backend, create, verbose, *args, **kwargs)
724 """!Delete and close all known display
726 return Display.delAllDisplays()
def getMaskTransparency
Return the current display's mask transparency.
def getDisplay
Return the Display indexed by frame, creating it if needs be.
def setMaskTransparency
Specify display's mask transparency (percent); or None to not set it when loading masks...
def interact
Enter an interactive loop, listening for key presses in display and firing callbacks.
A class to contain the data, WCS, and other information needed to describe an image of the sky...
def setMaskPlaneColor
Request that mask plane name be displayed as color.
def zoom
Zoom frame by specified amount, optionally panning also.
def setDefaultMaskTransparency
def delAllDisplays
Delete and close all known display.
def mtv
Display an Image or Mask on a DISPLAY display.
def __enter__
Support for python's with statement.
def pan
Pan to (rowc, colc); see also zoom.
def verbose
The backend's verbosity.
def __init__
Create an object able to display images and overplot glyphs.
def getMaskPlaneColor
Return the colour associated with the specified mask plane name.
A class to handle events such as key presses in image display windows.
Represent a 2-dimensional array of bitmask pixels.
def setDefaultMaskTransparency
def dot
Draw a symbol onto the specified DISPLAY frame at (col,row) = (c,r) [0-based coordinates].
A class to manipulate images, masks, and variance as a single object.
def scale
Set the range of the scaling from DN in the image to the image display.
def delAllDisplays
Delete and close all known display.
def show
Uniconify and Raise display.
def line
Draw a set of symbols or connect the points, a list of (col,row) If symbs is True, draw points at the specified points using the desired symbol, otherwise connect the dots.
def setCallback
Set the callback for key k to be func, returning the old callback.
def erase
Erase the specified DISPLAY frame.
def getDisplay
Return the Display indexed by frame, creating it if needs be.
def flush
Flush the buffers.
def __exit__
Support for python's with statement.
std::shared_ptr< Wcs > makeWcs(std::shared_ptr< daf::base::PropertySet > const &_metadata, bool stripMetadata)
def getActiveCallbackKeys
Return all callback keys.
def noop_callback
Callback function: arguments key, x, y.
def maskColorGenerator
A generator for "standard" colours.
A class to represent a 2-dimensional array of pixels.
def setDefaultMaskPlaneColor
Set the default mapping from mask plane names to colours.
def setDefaultMaskPlaneColor
Set the default mapping from mask plane names to colours.
A container for an Image and its associated metadata.