37 "WHITE",
"BLACK",
"RED",
"GREEN",
"BLUE",
"CYAN",
"MAGENTA",
"YELLOW",
"ORANGE",
"IGNORE",
38 "Display",
"Event",
"noop_callback",
"h_callback",
39 "setDefaultBackend",
"getDefaultBackend",
40 "setDefaultFrame",
"getDefaultFrame",
"incrDefaultFrame",
41 "setDefaultMaskTransparency",
"setDefaultMaskPlaneColor",
42 "getDisplay",
"delAllDisplays",
60 def _makeDisplayImpl(display, backend, *args, **kwargs):
61 """!Return the DisplayImpl for the named backend 63 @param display Name of device. Should be importable, either absolutely or relative to lsst.display 64 @param backend The desired backend 65 @param args Arguments passed to DisplayImpl.__init__ 66 @param kwargs Keywords arguments passed to DisplayImpl.__init__ 69 import lsst.afw.display as afwDisplay 70 display = afwDisplay.Display(display=1, backend="ds9") 72 _makeDisplayImpl(..., "ds9", 1) 73 and import the ds9 implementation of DisplayImpl from lsst.display.ds9 77 for dt
in (
"lsst.display.%s" % backend, backend,
".%s" % backend,
"lsst.afw.display.%s" % backend):
81 if dt.startswith(
"."):
82 impargs[
"package"] =
"lsst.display" 84 _disp = importlib.import_module(dt, **impargs)
86 except (ImportError, SystemError)
as e:
92 if not _disp
or not hasattr(_disp.DisplayImpl,
"_show"):
98 "Could not load the requested backend: {}".format(backend))
101 _impl = _disp.DisplayImpl(display, *args, **kwargs)
102 if not hasattr(_impl,
"frame"):
103 _impl.frame = display.frame
112 _defaultBackend =
None 114 _defaultMaskPlaneColor = dict(
121 DETECTED_NEGATIVE=CYAN,
128 _defaultMaskTransparency = {}
129 _defaultImageColormap =
"gray" 131 def __init__(self, frame=None, backend=None, *args, **kwargs):
132 """!Create an object able to display images and overplot glyphs 134 @param frame An identifier for the display 135 @param backend The backend to use (defaults to value set by setDefaultBackend()) 136 @param args Arguments to pass to the backend 137 @param kwargs Arguments to pass to the backend 143 if Display._defaultBackend
is None:
149 backend = Display._defaultBackend
152 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):
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 getattr(self,
"_impl",
None)
is not None:
226 if self.
frame in Display._displays:
227 del Display._displays[self.
frame]
231 """!The backend's verbosity""" 232 return self.
_impl.verbose
237 self.
_impl.verbose = value
240 return "Display[%s]" % (self.
frame)
248 _makeDisplayImpl(
None, backend)
249 except Exception
as e:
251 "Unable to set backend to %s: \"%s\"" % (backend, e))
253 Display._defaultBackend = backend
257 return Display._defaultBackend
261 """Set the default frame for display""" 262 Display._defaultFrame = frame
266 """Get the default frame for display""" 267 return Display._defaultFrame
271 """Increment the default frame for display""" 272 Display._defaultFrame += 1
273 return Display._defaultFrame
277 if hasattr(maskPlaneTransparency,
"copy"):
278 maskPlaneTransparency = maskPlaneTransparency.copy()
280 Display._defaultMaskTransparency = maskPlaneTransparency
284 """!Set the default mapping from mask plane names to colours 285 @param name name of mask plane, or a dict mapping names to colours 286 @param color Desired color, or None if name is a dict 288 If name is None, use the hard-coded default dictionary 292 name = Display._defaultMaskPlaneColor
294 if isinstance(name, dict):
296 for k, v
in name.items():
302 Display._defaultMaskPlaneColor[name] = color
306 """!Set the default colourmap for images 307 @param cmap Name of colourmap, as interpreted by the backend 309 The only colourmaps that all backends are required to honour 310 (if they pay any attention to setImageColormap) are "gray" and "grey" 313 Display._defaultImageColormap = cmap
316 """!Set the colourmap to use for images 317 @param cmap Name of colourmap, as interpreted by the backend 319 The only colourmaps that all backends are required to honour 320 (if they pay any attention to setImageColormap) are "gray" and "grey" 323 self.
_impl._setImageColormap(cmap)
326 def getDisplay(frame=None, backend=None, create=True, verbose=False, *args, **kwargs):
327 """!Return the Display indexed by frame, creating it if needs be 329 @param frame The desired frame (None => use defaultFrame (see setDefaultFrame)) 330 @param backend create the specified frame using this backend (or the default if None) \ 331 if it doesn't already exist. If backend == "", it's an error to specify a non-existent frame 332 @param create create the display if it doesn't already exist. 333 @param verbose Allow backend to be chatty 334 @param args arguments passed to Display constructor 335 @param kwargs keyword arguments passed to Display constructor 339 frame = Display._defaultFrame
341 if frame
not in Display._displays:
343 raise RuntimeError(
"Frame %s does not exist" % frame)
345 Display._displays[frame] =
Display(
346 frame, backend, verbose=verbose, *args, **kwargs)
348 Display._displays[frame].verbose = verbose
349 return Display._displays[frame]
353 """!Delete and close all known display 355 for disp
in list(Display._displays.values()):
357 Display._displays = {}
360 """!A generator for "standard" colours 362 @param omitBW Don't include Black and White 365 colorGenerator = interface.maskColorGenerator(omitBW=True) 367 print p, next(colorGenerator) 369 _maskColors = [WHITE, BLACK, RED, GREEN,
370 BLUE, CYAN, MAGENTA, YELLOW, ORANGE]
375 color = _maskColors[i%len(_maskColors)]
376 if omitBW
and color
in (BLACK, WHITE):
382 """!Request that mask plane name be displayed as color 384 @param name Name of mask plane or a dictionary of name -> colourName 385 @param color The name of the colour to use (must be None if name is a dict) 387 Colours may be specified as any X11-compliant string (e.g. <tt>"orchid"</tt>), or by one 388 of the following constants defined in @c afwDisplay: @c BLACK, @c WHITE, @c RED, @c BLUE, 389 @c GREEN, @c CYAN, @c MAGENTA, @c YELLOW. 391 If the colour is "ignore" (or @c IGNORE) then that mask plane is not displayed 393 The advantage of using the symbolic names is that the python interpreter can detect typos. 397 if isinstance(name, dict):
399 for k, v
in name.items():
406 """!Return the colour associated with the specified mask plane name 408 @param name Desired mask plane; if None, return entire dict 417 """!Specify display's mask transparency (percent); or None to not set it when loading masks""" 419 if isinstance(transparency, dict):
421 for k, v
in transparency.items():
425 if transparency
is not None and (transparency < 0
or transparency > 100):
427 "Mask transparency should be in the range [0, 100]; clipping", file=sys.stderr)
433 if transparency
is not None:
434 self.
_impl._setMaskTransparency(transparency, name)
437 """!Return the current display's mask transparency""" 439 return self.
_impl._getMaskTransparency(name)
442 """!Uniconify and Raise display. N.b. throws an exception if frame doesn't exit""" 443 return self.
_impl._show()
445 def mtv(self, data, title="", wcs=None):
446 """!Display an Image or Mask on a DISPLAY display 448 Historical note: the name "mtv" comes from Jim Gunn's forth imageprocessing 449 system, Mirella (named after Mirella Freni); The "m" stands for Mirella. 451 if hasattr(data,
"getXY0"):
452 self.
_xy0 = data.getXY0()
460 "You may not specify a wcs with an Exposure")
461 data, wcs = data.getMaskedImage(), data.getWcs()
464 wcs = afwGeom.makeSkyWcs(data.getMetadata())
469 self.
_xy0 = data.getXY0()
472 self.
_impl._mtv(data,
None, wcs, title)
479 self.
_impl._mtv(afwImage.ImageI(data.getArray()), data, wcs, title)
482 self.
_impl._mtv(data.getImage(), data.getMask(), wcs, title)
484 raise RuntimeError(
"Unsupported type %s" % repr(data))
490 """A class intended to be used with python's with statement""" 496 self.
_impl._buffer(
True)
499 self.
_impl._buffer(
False)
503 """Return a class intended to be used with python's with statement 505 with display.Buffering(): 506 display.dot("+", xc, yc) 511 """!Flush the buffers""" 515 """!Erase the specified DISPLAY frame 519 def dot(self, symb, c, r, size=2, ctype=None, origin=afwImage.PARENT, *args, **kwargs):
520 """!Draw a symbol onto the specified DISPLAY frame at (col,row) = (c,r) 521 [0-based coordinates] 528 @:Mxx,Mxy,Myy Draw an ellipse with moments (Mxx, Mxy, Myy) (argument size is ignored) 529 An object derived from afwGeom.ellipses.BaseCore Draw the ellipse (argument size is ignored) 530 Any other value is interpreted as a string to be drawn. Strings obey the fontFamily (which may be 531 extended with other characteristics, e.g. "times bold italic". Text will be drawn rotated by 532 textAngle (textAngle is ignored otherwise). 534 N.b. objects derived from BaseCore include Axes and Quadrupole. 536 if isinstance(symb, int):
539 if origin == afwImage.PARENT
and self.
_xy0 is not None:
544 if isinstance(symb, afwGeom.ellipses.BaseCore)
or re.search(
r"^@:", symb):
546 mat = re.search(
r"^@:([^,]+),([^,]+),([^,]+)", symb)
551 mxx, mxy, myy = [float(_)
for _
in mat.groups()]
552 symb = afwGeom.Quadrupole(mxx, myy, mxy)
554 symb = afwGeom.ellipses.Axes(symb)
556 self.
_impl._dot(symb, c, r, size, ctype, **kwargs)
558 def line(self, points, origin=afwImage.PARENT, symbs=False, ctype=None, size=0.5):
559 """!Draw a set of symbols or connect the points, a list of (col,row) 560 If symbs is True, draw points at the specified points using the desired symbol, 561 otherwise connect the dots. Ctype is the name of a colour (e.g. 'red') 563 If symbs supports indexing (which includes a string -- caveat emptor) the 564 elements are used to label the points 570 symbs = len(points)*
list(symbs)
572 for i, xy
in enumerate(points):
573 self.
dot(symbs[i], *xy, size=size, ctype=ctype)
576 if origin == afwImage.PARENT
and self.
_xy0 is not None:
578 _points =
list(points)
579 for i, p
in enumerate(points):
580 _points[i] = (p[0] - x0, p[1] - y0)
583 self.
_impl._drawLines(points, ctype)
588 def scale(self, algorithm, min, max=None, unit=None, *args, **kwargs):
589 """!Set the range of the scaling from DN in the image to the image display 590 @param algorithm Desired scaling (e.g. "linear" or "asinh") 591 @param min Minimum value, or "minmax" or "zscale" 592 @param max Maximum value (must be None for minmax|zscale) 593 @param unit Units for min and max (e.g. Percent, Absolute, Sigma; None if min==minmax|zscale) 594 @param *args Optional arguments 595 @param **kwargs Optional keyword arguments 597 if min
in (
"minmax",
"zscale"):
598 assert max
is None,
"You may not specify \"%s\" and max" % min
599 assert unit
is None,
"You may not specify \"%s\" and unit" % min
601 raise RuntimeError(
"Please specify max")
603 self.
_impl._scale(algorithm, min, max, unit, *args, **kwargs)
608 def zoom(self, zoomfac=None, colc=None, rowc=None, origin=afwImage.PARENT):
609 """!Zoom frame by specified amount, optionally panning also""" 611 if (rowc
and colc
is None)
or (colc
and rowc
is None):
613 "Please specify row and column center to pan about")
616 if origin == afwImage.PARENT
and self.
_xy0 is not None:
621 self.
_impl._pan(colc, rowc)
623 if zoomfac
is None and rowc
is None:
626 if zoomfac
is not None:
627 self.
_impl._zoom(zoomfac)
629 def pan(self, colc=None, rowc=None, origin=afwImage.PARENT):
630 """!Pan to (rowc, colc); see also zoom""" 632 self.
zoom(
None, colc, rowc, origin)
635 """!Enter an interactive loop, listening for key presses in display and firing callbacks. 636 Exit with q, @c CR, @c ESC, or any other callback function that returns a ``True`` value. 638 interactFinished =
False 640 while not interactFinished:
641 ev = self.
_impl._getEvent()
644 k, x, y = ev.k, ev.x, ev.y
647 logger.warn(
"No callback registered for {0}".format(k))
650 interactFinished = self.
_callbacks[k](k, x, y)
651 except Exception
as e:
653 "Display._callbacks['{0}']({0},{1},{2}) failed: {3}".format(k, x, y, e))
656 """!Set the callback for key k to be func, returning the old callback 663 "Key '%s' is already in use by display, so I can't add a callback for it" % k)
666 self.
_callbacks[k] = func
if func
else noop_callback
673 """!Return all callback keys 674 @param onlyActive If true only return keys that do something 678 not (onlyActive
and func == noop_callback)])
686 """!A class to handle events such as key presses in image display windows""" 688 def __init__(self, k, x=float(
'nan'), y=float(
'nan')):
694 return "%s (%.2f, %.2f)" % (self.
k, self.
x, self.
y)
701 """!Callback function: arguments key, x, y""" 706 print(
"Enter q or <ESC> to leave interactive mode, h for this help, or a letter to fire a callback")
717 Display.setDefaultBackend(backend)
721 return Display.getDefaultBackend()
725 return Display.setDefaultFrame(frame)
729 """Get the default frame for display""" 730 return Display.getDefaultFrame()
734 """Increment the default frame for display""" 735 return Display.incrDefaultFrame()
739 return Display.setDefaultMaskTransparency(maskPlaneTransparency)
743 """!Set the default mapping from mask plane names to colours 744 @param name name of mask plane, or a dict mapping names to colours 745 @param color Desired color, or None if name is a dict 747 If name is None, use the hard-coded default dictionary 750 return Display.setDefaultMaskPlaneColor(name, color)
753 def getDisplay(frame=None, backend=None, create=True, verbose=False, *args, **kwargs):
754 """!Return the Display indexed by frame, creating it if needs be 756 See Display.getDisplay 758 @param frame The desired frame (None => use defaultFrame (see setDefaultFrame)) 759 @param backend create the specified frame using this backend (or the default if None) \ 760 if it doesn't already exist. If backend == "", it's an error to specify a non-existent frame 761 @param create create the display if it doesn't already exist. 762 @param verbose Allow backend to be chatty 763 @param args arguments passed to Display constructor 764 @param kwargs keyword arguments passed to Display constructor 767 return Display.getDisplay(frame, backend, create, verbose, *args, **kwargs)
771 """!Delete and close all known display 773 return Display.delAllDisplays()
def pan(self, colc=None, rowc=None, origin=afwImage.PARENT)
Pan to (rowc, colc); see also zoom.
def dot(self, symb, c, r, size=2, ctype=None, origin=afwImage.PARENT, args, kwargs)
Draw a symbol onto the specified DISPLAY frame at (col,row) = (c,r) [0-based coordinates].
def maskColorGenerator(self, omitBW=True)
A generator for "standard" colours.
def verbose(self)
The backend's verbosity.
def setImageColormap(self, cmap)
Set the colourmap to use for images.
def getDisplay(frame=None, backend=None, create=True, verbose=False, args, kwargs)
Return the Display indexed by frame, creating it if needs be.
def noop_callback(k, x, y)
Callback function: arguments key, x, y.
std::vector< SchemaItem< Flag > > * items
A class to contain the data, WCS, and other information needed to describe an image of the sky...
def setDefaultMaskPlaneColor(name=None, color=None)
Set the default mapping from mask plane names to colours.
def __getattr__(self, name)
def setDefaultMaskTransparency(maskPlaneTransparency={})
def getDisplay(frame=None, backend=None, create=True, verbose=False, args, kwargs)
Return the Display indexed by frame, creating it if needs be.
def setCallback(self, k, func=None, noRaise=False)
Set the callback for key k to be func, returning the old callback.
def __init__(self, k, x=float('nan'), y=float('nan'))
def setDefaultImageColormap(cmap)
Set the default colourmap for images.
def erase(self)
Erase the specified DISPLAY frame.
def flush(self)
Flush the buffers.
def delAllDisplays()
Delete and close all known display.
def getActiveCallbackKeys(self, onlyActive=True)
Return all callback keys.
A class to handle events such as key presses in image display windows.
Represent a 2-dimensional array of bitmask pixels.
def getMaskPlaneColor(self, name=None)
Return the colour associated with the specified mask plane name.
def setDefaultFrame(frame=0)
def setDefaultBackend(backend)
def __enter__(self)
Support for python's with statement.
def scale(self, algorithm, min, max=None, unit=None, args, kwargs)
Set the range of the scaling from DN in the image to the image display.
A class to manipulate images, masks, and variance as a single object.
def __init__(self, _impl)
def __init__(self, frame=None, backend=None, args, kwargs)
Create an object able to display images and overplot glyphs.
def mtv(self, data, title="", wcs=None)
Display an Image or Mask on a DISPLAY display.
def __exit__(self, args)
Support for python's with statement.
def setDefaultMaskPlaneColor(name=None, color=None)
Set the default mapping from mask plane names to colours.
def line(self, points, origin=afwImage.PARENT, symbs=False, ctype=None, size=0.5)
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 setMaskPlaneColor(self, name, color=None)
Request that mask plane name be displayed as color.
def getMaskTransparency(self, name=None)
Return the current display's mask transparency.
def delAllDisplays()
Delete and close all known display.
def setDefaultBackend(backend)
def interact(self)
Enter an interactive loop, listening for key presses in display and firing callbacks.
daf::base::PropertyList * list
def setDefaultFrame(frame=0)
static Log getLogger(std::string const &loggername)
def setMaskTransparency(self, transparency=None, name=None)
Specify display's mask transparency (percent); or None to not set it when loading masks...
def zoom(self, zoomfac=None, colc=None, rowc=None, origin=afwImage.PARENT)
Zoom frame by specified amount, optionally panning also.
A class to represent a 2-dimensional array of pixels.
def setDefaultMaskTransparency(maskPlaneTransparency={})
A container for an Image and its associated metadata.
def show(self)
Uniconify and Raise display.