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 """Return the attribute of self._impl, or ._impl if it is requested
201 name of the attribute requested
205 the attribute of self._impl for the requested name
209 return object.__getattr__(self, name)
211 if not (hasattr(self,
"_impl")
and self.
_impl):
212 raise AttributeError(
"Device has no _impl attached")
215 return getattr(self.
_impl, name)
216 except AttributeError:
217 raise AttributeError(
218 "Device %s has no attribute \"%s\"" % (self.
name, name))
221 if hasattr(self,
"_impl")
and self.
_impl:
225 if self.
frame in Display._displays:
226 del Display._displays[self.
frame]
230 """!The backend's verbosity"""
231 return self._impl.verbose
236 self._impl.verbose = value
239 return "Display[%s]" % (self.
frame)
247 _makeDisplayImpl(
None, backend)
248 except Exception
as e:
250 "Unable to set backend to %s: \"%s\"" % (backend, e))
252 Display._defaultBackend = backend
256 return Display._defaultBackend
260 """Set the default frame for display"""
261 Display._defaultFrame = frame
265 """Get the default frame for display"""
266 return Display._defaultFrame
270 """Increment the default frame for display"""
271 Display._defaultFrame += 1
272 return Display._defaultFrame
276 if hasattr(maskPlaneTransparency,
"copy"):
277 maskPlaneTransparency = maskPlaneTransparency.copy()
279 Display._defaultMaskTransparency = maskPlaneTransparency
283 """!Set the default mapping from mask plane names to colours
284 \param name name of mask plane, or a dict mapping names to colours
285 \param color Desired color, or None if name is a dict
287 If name is None, use the hard-coded default dictionary
291 name = Display._defaultMaskPlaneColor
293 if isinstance(name, dict):
295 for k, v
in name.items():
301 Display._defaultMaskPlaneColor[name] = color
304 def getDisplay(frame=None, backend=None, create=True, verbose=False, *args, **kwargs):
305 """!Return the Display indexed by frame, creating it if needs be
307 \param frame The desired frame (None => use defaultFrame (see setDefaultFrame))
308 \param backend create the specified frame using this backend (or the default if None) \
309 if it doesn't already exist. If backend == "", it's an error to specify a non-existent frame
310 \param create create the display if it doesn't already exist.
311 \param verbose Allow backend to be chatty
312 \param args arguments passed to Display constructor
313 \param kwargs keyword arguments passed to Display constructor
317 frame = Display._defaultFrame
319 if frame
not in Display._displays:
321 raise RuntimeError(
"Frame %s does not exist" % frame)
323 Display._displays[frame] =
Display(
324 frame, backend, verbose=verbose, *args, **kwargs)
326 Display._displays[frame].verbose = verbose
327 return Display._displays[frame]
331 """!Delete and close all known display
333 for disp
in list(Display._displays.values()):
335 Display._displays = {}
338 """!A generator for "standard" colours
340 \param omitBW Don't include Black and White
343 colorGenerator = interface.maskColorGenerator(omitBW=True)
345 print p, next(colorGenerator)
347 _maskColors = [WHITE, BLACK, RED, GREEN,
348 BLUE, CYAN, MAGENTA, YELLOW, ORANGE]
353 color = _maskColors[i%len(_maskColors)]
354 if omitBW
and color
in (BLACK, WHITE):
360 """!Request that mask plane name be displayed as color
362 \param name Name of mask plane or a dictionary of name -> colourName
363 \param color The name of the colour to use (must be None if name is a dict)
365 Colours may be specified as any X11-compliant string (e.g. <tt>"orchid"</tt>), or by one
366 of the following constants defined in \c afwDisplay: \c BLACK, \c WHITE, \c RED, \c BLUE,
367 \c GREEN, \c CYAN, \c MAGENTA, \c YELLOW.
369 The advantage of using the symbolic names is that the python interpreter can detect typos.
373 if isinstance(name, dict):
375 for k, v
in name.items():
382 """!Return the colour associated with the specified mask plane name"""
384 return self._maskPlaneColors.get(name)
387 """!Specify display's mask transparency (percent); or None to not set it when loading masks"""
389 if isinstance(transparency, dict):
391 for k, v
in transparency.items():
395 if transparency
is not None and (transparency < 0
or transparency > 100):
397 "Mask transparency should be in the range [0, 100]; clipping", file=sys.stderr)
403 if transparency
is not None:
404 self._impl._setMaskTransparency(transparency, name)
407 """!Return the current display's mask transparency"""
409 return self._impl._getMaskTransparency(name)
412 """!Uniconify and Raise display. N.b. throws an exception if frame doesn't exit"""
413 return self._impl._show()
415 def mtv(self, data, title="", wcs=None):
416 """!Display an Image or Mask on a DISPLAY display
418 Historical note: the name "mtv" comes from Jim Gunn's forth imageprocessing
419 system, Mirella (named after Mirella Freni); The "m" stands for Mirella.
421 if hasattr(data,
"getXY0"):
422 self.
_xy0 = data.getXY0()
430 "You may not specify a wcs with an Exposure")
431 data, wcs = data.getMaskedImage(), data.getWcs()
434 self.
_xy0 = data.getXY0()
437 self._impl._mtv(data,
None, wcs, title)
444 self._impl._mtv(afwImage.ImageU(data.getArray()), data, wcs, title)
447 self._impl._mtv(data.getImage(), data.getMask(), wcs, title)
449 raise RuntimeError(
"Unsupported type %s" % repr(data))
455 """A class intended to be used with python's with statement"""
461 self._impl._buffer(
True)
464 self._impl._buffer(
False)
468 """Return a class intended to be used with python's with statement
470 with display.Buffering():
471 display.dot("+", xc, yc)
476 """!Flush the buffers"""
480 """!Erase the specified DISPLAY frame
484 def dot(self, symb, c, r, size=2, ctype=None, origin=afwImage.PARENT, *args, **kwargs):
485 """!Draw a symbol onto the specified DISPLAY frame at (col,row) = (c,r)
486 [0-based coordinates]
493 @:Mxx,Mxy,Myy Draw an ellipse with moments (Mxx, Mxy, Myy) (argument size is ignored)
494 An object derived from afwGeom.ellipses.BaseCore Draw the ellipse (argument size is ignored)
495 Any other value is interpreted as a string to be drawn. Strings obey the fontFamily (which may be
496 extended with other characteristics, e.g. "times bold italic". Text will be drawn rotated by
497 textAngle (textAngle is ignored otherwise).
499 N.b. objects derived from BaseCore include Axes and Quadrupole.
501 if isinstance(symb, int):
504 if origin == afwImage.PARENT
and self.
_xy0 is not None:
509 if isinstance(symb, afwGeom.ellipses.BaseCore)
or re.search(
r"^@:", symb):
511 mat = re.search(
r"^@:([^,]+),([^,]+),([^,]+)", symb)
516 mxx, mxy, myy = [float(_)
for _
in mat.groups()]
517 symb = afwGeom.ellipses.Quadrupole(mxx, myy, mxy)
519 symb = afwGeom.ellipses.Axes(symb)
521 self._impl._dot(symb, c, r, size, ctype, **kwargs)
523 def line(self, points, origin=afwImage.PARENT, symbs=False, ctype=None, size=0.5):
524 """!Draw a set of symbols or connect the points, a list of (col,row)
525 If symbs is True, draw points at the specified points using the desired symbol,
526 otherwise connect the dots. Ctype is the name of a colour (e.g. 'red')
528 If symbs supports indexing (which includes a string -- caveat emptor) the
529 elements are used to label the points
535 symbs = len(points)*list(symbs)
537 for i, xy
in enumerate(points):
538 self.
dot(symbs[i], *xy, size=size, ctype=ctype)
541 if origin == afwImage.PARENT
and self.
_xy0 is not None:
543 _points = list(points)
544 for i, p
in enumerate(points):
545 _points[i] = (p[0] - x0, p[1] - y0)
548 self._impl._drawLines(points, ctype)
553 def scale(self, algorithm, min, max=None, unit=None, *args, **kwargs):
554 """!Set the range of the scaling from DN in the image to the image display
555 \param algorithm Desired scaling (e.g. "linear" or "asinh")
556 \param min Minimum value, or "minmax" or "zscale"
557 \param max Maximum value (must be None for minmax|zscale)
558 \param unit Units for min and max (e.g. Percent, Absolute, Sigma; None if min==minmax|zscale)
559 \param *args Optional arguments
560 \param **kwargs Optional keyword arguments
562 if min
in (
"minmax",
"zscale"):
563 assert max
is None,
"You may not specify \"%s\" and max" % min
564 assert unit
is None,
"You may not specify \"%s\" and unit" % min
566 raise RuntimeError(
"Please specify max")
568 self._impl._scale(algorithm, min, max, unit, *args, **kwargs)
573 def zoom(self, zoomfac=None, colc=None, rowc=None, origin=afwImage.PARENT):
574 """!Zoom frame by specified amount, optionally panning also"""
576 if (rowc
and colc
is None)
or (colc
and rowc
is None):
578 "Please specify row and column center to pan about")
581 if origin == afwImage.PARENT
and self.
_xy0 is not None:
586 self._impl._pan(colc, rowc)
588 if zoomfac
is None and rowc
is None:
591 if zoomfac
is not None:
592 self._impl._zoom(zoomfac)
594 def pan(self, colc=None, rowc=None, origin=afwImage.PARENT):
595 """!Pan to (rowc, colc); see also zoom"""
597 self.
zoom(
None, colc, rowc, origin)
600 """!Enter an interactive loop, listening for key presses in display and firing callbacks.
601 Exit with q, \c CR, \c ESC, or any other callback function that returns a ``True`` value.
603 interactFinished =
False
605 while not interactFinished:
606 ev = self._impl._getEvent()
609 k, x, y = ev.k, ev.x, ev.y
612 logger.warn(
"No callback registered for {0}".format(k))
615 interactFinished = self.
_callbacks[k](k, x, y)
616 except Exception
as e:
618 "Display._callbacks[{0}]({0},{1},{2}) failed: {3}".format(k, x, y, e))
621 """!Set the callback for key k to be func, returning the old callback
628 "Key '%s' is already in use by display, so I can't add a callback for it" % k)
630 ofunc = self._callbacks.get(k)
631 self.
_callbacks[k] = func
if func
else noop_callback
633 self._impl._setCallback(k, self.
_callbacks[k])
638 """!Return all callback keys
639 \param onlyActive If true only return keys that do something
642 return sorted([k
for k, func
in self._callbacks.items()
if
643 not (onlyActive
and func == noop_callback)])
651 """!A class to handle events such as key presses in image display windows"""
653 def __init__(self, k, x=float(
'nan'), y=float(
'nan')):
659 return "%s (%.2f, %.2f)" % (self.
k, self.
x, self.
y)
666 """!Callback function: arguments key, x, y"""
671 print(
"Enter q or <ESC> to leave interactive mode, h for this help, or a letter to fire a callback")
682 Display.setDefaultBackend(backend)
686 return Display.getDefaultBackend()
690 return Display.setDefaultFrame(frame)
694 """Get the default frame for display"""
695 return Display.getDefaultFrame()
699 """Increment the default frame for display"""
700 return Display.incrDefaultFrame()
704 return Display.setDefaultMaskTransparency(maskPlaneTransparency)
708 """!Set the default mapping from mask plane names to colours
709 \param name name of mask plane, or a dict mapping names to colours
710 \param color Desired color, or None if name is a dict
712 If name is None, use the hard-coded default dictionary
715 return Display.setDefaultMaskPlaneColor(name, color)
718 def getDisplay(frame=None, backend=None, create=True, verbose=False, *args, **kwargs):
719 """!Return the Display indexed by frame, creating it if needs be
721 See Display.getDisplay
723 \param frame The desired frame (None => use defaultFrame (see setDefaultFrame))
724 \param backend create the specified frame using this backend (or the default if None) \
725 if it doesn't already exist. If backend == "", it's an error to specify a non-existent frame
726 \param create create the display if it doesn't already exist.
727 \param verbose Allow backend to be chatty
728 \param args arguments passed to Display constructor
729 \param kwargs keyword arguments passed to Display constructor
732 return Display.getDisplay(frame, backend, create, verbose, *args, **kwargs)
736 """!Delete and close all known display
738 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.