Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

# 

# LSST Data Management System 

# Copyright 2008, 2009, 2010, 2015 LSST Corporation. 

# 

# This product includes software developed by the 

# LSST Project (http://www.lsst.org/). 

# 

# This program is free software: you can redistribute it and/or modify 

# it under the terms of the GNU General Public License as published by 

# the Free Software Foundation, either version 3 of the License, or 

# (at your option) any later version. 

# 

# This program is distributed in the hope that it will be useful, 

# but WITHOUT ANY WARRANTY; without even the implied warranty of 

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

# GNU General Public License for more details. 

# 

# You should have received a copy of the LSST License Statement and 

# the GNU General Public License along with this program. If not, 

# see <http://www.lsstcorp.org/LegalNotices/>. 

# 

 

## 

# @file 

# @brief Support for talking to image displays from python 

 

import re 

import sys 

import importlib 

import lsst.afw.geom as afwGeom 

import lsst.afw.image as afwImage 

import lsst.log 

 

logger = lsst.log.Log.getLogger("afw.display.interface") 

 

__all__ = ( 

"WHITE", "BLACK", "RED", "GREEN", "BLUE", "CYAN", "MAGENTA", "YELLOW", "ORANGE", "IGNORE", 

"Display", "Event", "noop_callback", "h_callback", 

"setDefaultBackend", "getDefaultBackend", 

"setDefaultFrame", "getDefaultFrame", "incrDefaultFrame", 

"setDefaultMaskTransparency", "setDefaultMaskPlaneColor", 

"getDisplay", "delAllDisplays", 

) 

 

# 

# Symbolic names for mask/line colours. N.b. ds9 supports any X11 colour for masks 

# 

WHITE = "white" 

BLACK = "black" 

RED = "red" 

GREEN = "green" 

BLUE = "blue" 

CYAN = "cyan" 

MAGENTA = "magenta" 

YELLOW = "yellow" 

ORANGE = "orange" 

IGNORE = "ignore" 

 

 

def _makeDisplayImpl(display, backend, *args, **kwargs): 

"""!Return the DisplayImpl for the named backend 

 

@param display Name of device. Should be importable, either absolutely or relative to lsst.display 

@param backend The desired backend 

@param args Arguments passed to DisplayImpl.__init__ 

@param kwargs Keywords arguments passed to DisplayImpl.__init__ 

 

E.g. 

import lsst.afw.display as afwDisplay 

display = afwDisplay.Display(display=1, backend="ds9") 

would call 

_makeDisplayImpl(..., "ds9", 1) 

and import the ds9 implementation of DisplayImpl from lsst.display.ds9 

""" 

_disp = None 

exc = None 

for dt in ("lsst.display.%s" % backend, backend, ".%s" % backend, "lsst.afw.display.%s" % backend): 

exc = None 

# only specify the root package if we are not doing an absolute import 

impargs = {} 

if dt.startswith("."): 

impargs["package"] = "lsst.display" 

try: 

_disp = importlib.import_module(dt, **impargs) 

break 

except (ImportError, SystemError) as e: 

# SystemError can be raised in Python 3.5 if a relative import 

# is attempted when the root package, lsst.display, does not exist. 

# Copy the exception into outer scope 

exc = e 

 

if not _disp or not hasattr(_disp.DisplayImpl, "_show"): 

93 ↛ 97line 93 didn't jump to line 97, because the condition on line 93 was never false if exc is not None: 

# re-raise the final exception 

raise exc 

else: 

raise ImportError( 

"Could not load the requested backend: {}".format(backend)) 

 

if display: 

_impl = _disp.DisplayImpl(display, *args, **kwargs) 

102 ↛ 105line 102 didn't jump to line 105, because the condition on line 102 was never false if not hasattr(_impl, "frame"): 

_impl.frame = display.frame 

 

return _impl 

else: 

return True 

 

 

class Display: 

_displays = {} 

_defaultBackend = None 

_defaultFrame = 0 

_defaultMaskPlaneColor = dict( 

BAD=RED, 

CR=MAGENTA, 

EDGE=YELLOW, 

INTERPOLATED=GREEN, 

SATURATED=GREEN, 

DETECTED=BLUE, 

DETECTED_NEGATIVE=CYAN, 

SUSPECT=YELLOW, 

NO_DATA=ORANGE, 

# deprecated names 

INTRP=GREEN, 

SAT=GREEN, 

) 

_defaultMaskTransparency = {} 

 

def __init__(self, frame=None, backend=None, *args, **kwargs): 

"""!Create an object able to display images and overplot glyphs 

 

@param frame An identifier for the display 

@param backend The backend to use (defaults to value set by setDefaultBackend()) 

@param args Arguments to pass to the backend 

@param kwargs Arguments to pass to the backend 

""" 

138 ↛ 139line 138 didn't jump to line 139, because the condition on line 138 was never true if frame is None: 

frame = getDefaultFrame() 

 

if backend is None: 

142 ↛ 143line 142 didn't jump to line 143, because the condition on line 142 was never true if Display._defaultBackend is None: 

try: 

setDefaultBackend("ds9") 

except RuntimeError: 

setDefaultBackend("virtualDevice") 

 

backend = Display._defaultBackend 

 

self.frame = frame 

self._impl = _makeDisplayImpl(self, backend, *args, **kwargs) 

self.name = backend 

 

self._xy0 = None # displayed data's XY0 

self.setMaskTransparency(Display._defaultMaskTransparency) 

self._maskPlaneColors = {} 

self.setMaskPlaneColor(Display._defaultMaskPlaneColor) 

 

self._callbacks = {} 

 

for ik in range(ord('a'), ord('z') + 1): 

k = "%c" % ik 

self.setCallback(k, noRaise=True) 

self.setCallback(k.upper(), noRaise=True) 

 

for k in ('Return', 'Shift_L', 'Shift_R'): 

self.setCallback(k) 

 

for k in ('q', 'Escape'): 

self.setCallback(k, lambda k, x, y: True) 

 

def _h_callback(k, x, y): 

h_callback(k, x, y) 

 

for k in sorted(self._callbacks.keys()): 

doc = self._callbacks[k].__doc__ 

print(" %-6s %s" % (k, doc.split("\n")[0] if doc else "???")) 

 

self.setCallback('h', _h_callback) 

 

Display._displays[frame] = self 

 

def __enter__(self): 

"""!Support for python's with statement""" 

return self 

 

def __exit__(self, *args): 

"""!Support for python's with statement""" 

self.close() 

 

def __del__(self): 

self.close() 

 

def __getattr__(self, name): 

"""Return the attribute of self._impl, or ._impl if it is requested 

Parameters: 

----------- 

name : string 

name of the attribute requested 

Returns: 

-------- 

attribute : object 

the attribute of self._impl for the requested name 

""" 

 

if name == '_impl': 

return object.__getattr__(self, name) 

 

if not (hasattr(self, "_impl") and self._impl): 

raise AttributeError("Device has no _impl attached") 

 

try: 

return getattr(self._impl, name) 

except AttributeError: 

raise AttributeError( 

"Device %s has no attribute \"%s\"" % (self.name, name)) 

 

def close(self): 

if getattr(self, "_impl", None) is not None: 

self._impl._close() 

del self._impl 

self._impl = None 

 

if self.frame in Display._displays: 

del Display._displays[self.frame] 

 

@property 

def verbose(self): 

"""!The backend's verbosity""" 

return self._impl.verbose 

 

@verbose.setter 

def verbose(self, value): 

234 ↛ exitline 234 didn't return from function 'verbose', because the condition on line 234 was never false if self._impl: 

self._impl.verbose = value 

 

def __str__(self): 

return "Display[%s]" % (self.frame) 

 

# 

# Handle Displays, including the default one (the frame to use when a user specifies None) 

# 

@staticmethod 

def setDefaultBackend(backend): 

try: 

_makeDisplayImpl(None, backend) 

except Exception as e: 

raise RuntimeError( 

"Unable to set backend to %s: \"%s\"" % (backend, e)) 

 

Display._defaultBackend = backend 

 

@staticmethod 

def getDefaultBackend(): 

return Display._defaultBackend 

 

@staticmethod 

def setDefaultFrame(frame=0): 

"""Set the default frame for display""" 

Display._defaultFrame = frame 

 

@staticmethod 

def getDefaultFrame(): 

"""Get the default frame for display""" 

return Display._defaultFrame 

 

@staticmethod 

def incrDefaultFrame(): 

"""Increment the default frame for display""" 

Display._defaultFrame += 1 

return Display._defaultFrame 

 

@staticmethod 

def setDefaultMaskTransparency(maskPlaneTransparency={}): 

if hasattr(maskPlaneTransparency, "copy"): 

maskPlaneTransparency = maskPlaneTransparency.copy() 

 

Display._defaultMaskTransparency = maskPlaneTransparency 

 

@staticmethod 

def setDefaultMaskPlaneColor(name=None, color=None): 

"""!Set the default mapping from mask plane names to colours 

@param name name of mask plane, or a dict mapping names to colours 

@param color Desired color, or None if name is a dict 

 

If name is None, use the hard-coded default dictionary 

""" 

 

if name is None: 

name = Display._defaultMaskPlaneColor 

 

if isinstance(name, dict): 

assert color is None 

for k, v in name.items(): 

setDefaultMaskPlaneColor(k, v) 

return 

# 

# Set the individual colour values 

# 

Display._defaultMaskPlaneColor[name] = color 

 

@staticmethod 

def getDisplay(frame=None, backend=None, create=True, verbose=False, *args, **kwargs): 

"""!Return the Display indexed by frame, creating it if needs be 

 

@param frame The desired frame (None => use defaultFrame (see setDefaultFrame)) 

@param backend create the specified frame using this backend (or the default if None) \ 

if it doesn't already exist. If backend == "", it's an error to specify a non-existent frame 

@param create create the display if it doesn't already exist. 

@param verbose Allow backend to be chatty 

@param args arguments passed to Display constructor 

@param kwargs keyword arguments passed to Display constructor 

""" 

 

315 ↛ 316line 315 didn't jump to line 316, because the condition on line 315 was never true if frame is None: 

frame = Display._defaultFrame 

 

if frame not in Display._displays: 

319 ↛ 320line 319 didn't jump to line 320, because the condition on line 319 was never true if backend == "": 

raise RuntimeError("Frame %s does not exist" % frame) 

 

Display._displays[frame] = Display( 

frame, backend, verbose=verbose, *args, **kwargs) 

 

Display._displays[frame].verbose = verbose 

return Display._displays[frame] 

 

@staticmethod 

def delAllDisplays(): 

"""!Delete and close all known display 

""" 

for disp in list(Display._displays.values()): 

disp.close() 

Display._displays = {} 

 

def maskColorGenerator(self, omitBW=True): 

"""!A generator for "standard" colours 

 

@param omitBW Don't include Black and White 

 

e.g. 

colorGenerator = interface.maskColorGenerator(omitBW=True) 

for p in planeList: 

print p, next(colorGenerator) 

""" 

_maskColors = [WHITE, BLACK, RED, GREEN, 

BLUE, CYAN, MAGENTA, YELLOW, ORANGE] 

 

i = -1 

while True: 

i += 1 

color = _maskColors[i%len(_maskColors)] 

if omitBW and color in (BLACK, WHITE): 

continue 

 

yield color 

 

def setMaskPlaneColor(self, name, color=None): 

"""!Request that mask plane name be displayed as color 

 

@param name Name of mask plane or a dictionary of name -> colourName 

@param color The name of the colour to use (must be None if name is a dict) 

 

Colours may be specified as any X11-compliant string (e.g. <tt>"orchid"</tt>), or by one 

of the following constants defined in @c afwDisplay: @c BLACK, @c WHITE, @c RED, @c BLUE, 

@c GREEN, @c CYAN, @c MAGENTA, @c YELLOW. 

 

If the colour is "ignore" (or @c IGNORE) then that mask plane is not displayed 

 

The advantage of using the symbolic names is that the python interpreter can detect typos. 

 

""" 

 

if isinstance(name, dict): 

assert color is None 

for k, v in name.items(): 

self.setMaskPlaneColor(k, v) 

return 

 

self._maskPlaneColors[name] = color 

 

def getMaskPlaneColor(self, name=None): 

"""!Return the colour associated with the specified mask plane name 

 

@param name Desired mask plane; if None, return entire dict 

""" 

 

if name is None: 

return self._maskPlaneColors 

else: 

return self._maskPlaneColors.get(name) 

 

def setMaskTransparency(self, transparency=None, name=None): 

"""!Specify display's mask transparency (percent); or None to not set it when loading masks""" 

 

if isinstance(transparency, dict): 

assert name is None 

398 ↛ 399line 398 didn't jump to line 399, because the loop on line 398 never started for k, v in transparency.items(): 

self.setMaskTransparency(k, v) 

return 

 

402 ↛ 403line 402 didn't jump to line 403, because the condition on line 402 was never true if transparency is not None and (transparency < 0 or transparency > 100): 

print( 

"Mask transparency should be in the range [0, 100]; clipping", file=sys.stderr) 

if transparency < 0: 

transparency = 0 

else: 

transparency = 100 

 

410 ↛ exitline 410 didn't return from function 'setMaskTransparency', because the condition on line 410 was never false if transparency is not None: 

self._impl._setMaskTransparency(transparency, name) 

 

def getMaskTransparency(self, name=None): 

"""!Return the current display's mask transparency""" 

 

return self._impl._getMaskTransparency(name) 

 

def show(self): 

"""!Uniconify and Raise display. N.b. throws an exception if frame doesn't exit""" 

return self._impl._show() 

 

def mtv(self, data, title="", wcs=None): 

"""!Display an Image or Mask on a DISPLAY display 

 

Historical note: the name "mtv" comes from Jim Gunn's forth imageprocessing 

system, Mirella (named after Mirella Freni); The "m" stands for Mirella. 

""" 

if hasattr(data, "getXY0"): 

self._xy0 = data.getXY0() 

else: 

self._xy0 = None 

 

# it's an Exposure; display the MaskedImage with the WCS 

if isinstance(data, afwImage.Exposure): 

435 ↛ 436line 435 didn't jump to line 436, because the condition on line 435 was never true if wcs: 

raise RuntimeError( 

"You may not specify a wcs with an Exposure") 

data, wcs = data.getMaskedImage(), data.getWcs() 

elif isinstance(data, afwImage.DecoratedImage): # it's a DecoratedImage; display it 

data, wcs = data.getImage(), afwGeom.makeSkyWcs(data.getMetadata()) 

self._xy0 = data.getXY0() # DecoratedImage doesn't have getXY0() 

 

if isinstance(data, afwImage.Image): # it's an Image; display it 

self._impl._mtv(data, None, wcs, title) 

# it's a Mask; display it, bitplane by bitplane 

elif isinstance(data, afwImage.Mask): 

# 

# Some displays can't display a Mask without an image; so display an Image too, 

# with pixel values set to the mask 

# 

self._impl._mtv(afwImage.ImageI(data.getArray()), data, wcs, title) 

# it's a MaskedImage; display Image and overlay Mask 

453 ↛ 456line 453 didn't jump to line 456, because the condition on line 453 was never false elif isinstance(data, afwImage.MaskedImage): 

self._impl._mtv(data.getImage(), data.getMask(), wcs, title) 

else: 

raise RuntimeError("Unsupported type %s" % repr(data)) 

# 

# Graphics commands 

# 

 

class _Buffering: 

"""A class intended to be used with python's with statement""" 

 

def __init__(self, _impl): 

self._impl = _impl 

 

def __enter__(self): 

self._impl._buffer(True) 

 

def __exit__(self, *args): 

self._impl._buffer(False) 

self._impl._flush() 

 

def Buffering(self): 

"""Return a class intended to be used with python's with statement 

E.g. 

with display.Buffering(): 

display.dot("+", xc, yc) 

""" 

return self._Buffering(self._impl) 

 

def flush(self): 

"""!Flush the buffers""" 

self._impl._flush() 

 

def erase(self): 

"""!Erase the specified DISPLAY frame 

""" 

self._impl._erase() 

 

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] 

 

Possible values are: 

+ Draw a + 

x Draw an x 

* Draw a * 

o Draw a circle 

@:Mxx,Mxy,Myy Draw an ellipse with moments (Mxx, Mxy, Myy) (argument size is ignored) 

An object derived from afwGeom.ellipses.BaseCore Draw the ellipse (argument size is ignored) 

Any other value is interpreted as a string to be drawn. Strings obey the fontFamily (which may be 

extended with other characteristics, e.g. "times bold italic". Text will be drawn rotated by 

textAngle (textAngle is ignored otherwise). 

 

N.b. objects derived from BaseCore include Axes and Quadrupole. 

""" 

508 ↛ 509line 508 didn't jump to line 509, because the condition on line 508 was never true if isinstance(symb, int): 

symb = "%d" % (symb) 

 

511 ↛ 516line 511 didn't jump to line 516, because the condition on line 511 was never false if origin == afwImage.PARENT and self._xy0 is not None: 

x0, y0 = self._xy0 

r -= y0 

c -= x0 

 

516 ↛ 517line 516 didn't jump to line 517, because the condition on line 516 was never true if isinstance(symb, afwGeom.ellipses.BaseCore) or re.search(r"^@:", symb): 

try: 

mat = re.search(r"^@:([^,]+),([^,]+),([^,]+)", symb) 

except TypeError: 

pass 

else: 

if mat: 

mxx, mxy, myy = [float(_) for _ in mat.groups()] 

symb = afwGeom.Quadrupole(mxx, myy, mxy) 

 

symb = afwGeom.ellipses.Axes(symb) 

 

self._impl._dot(symb, c, r, size, ctype, **kwargs) 

 

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. Ctype is the name of a colour (e.g. 'red') 

 

If symbs supports indexing (which includes a string -- caveat emptor) the 

elements are used to label the points 

""" 

if symbs: 

try: 

symbs[1] 

except TypeError: 

symbs = len(points)*list(symbs) 

 

for i, xy in enumerate(points): 

self.dot(symbs[i], *xy, size=size, ctype=ctype) 

else: 

547 ↛ exitline 547 didn't return from function 'line', because the condition on line 547 was never false if len(points) > 0: 

548 ↛ 555line 548 didn't jump to line 555, because the condition on line 548 was never false if origin == afwImage.PARENT and self._xy0 is not None: 

x0, y0 = self._xy0 

_points = list(points) # make a mutable copy 

for i, p in enumerate(points): 

_points[i] = (p[0] - x0, p[1] - y0) 

points = _points 

 

self._impl._drawLines(points, ctype) 

# 

# Set gray scale 

# 

 

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 

@param algorithm Desired scaling (e.g. "linear" or "asinh") 

@param min Minimum value, or "minmax" or "zscale" 

@param max Maximum value (must be None for minmax|zscale) 

@param unit Units for min and max (e.g. Percent, Absolute, Sigma; None if min==minmax|zscale) 

@param *args Optional arguments 

@param **kwargs Optional keyword arguments 

""" 

569 ↛ 572line 569 didn't jump to line 572, because the condition on line 569 was never false if min in ("minmax", "zscale"): 

assert max is None, "You may not specify \"%s\" and max" % min 

assert unit is None, "You may not specify \"%s\" and unit" % min 

elif max is None: 

raise RuntimeError("Please specify max") 

 

self._impl._scale(algorithm, min, max, unit, *args, **kwargs) 

# 

# Zoom and Pan 

# 

 

def zoom(self, zoomfac=None, colc=None, rowc=None, origin=afwImage.PARENT): 

"""!Zoom frame by specified amount, optionally panning also""" 

 

583 ↛ 584line 583 didn't jump to line 584, because the condition on line 583 was never true if (rowc and colc is None) or (colc and rowc is None): 

raise RuntimeError( 

"Please specify row and column center to pan about") 

 

if rowc is not None: 

588 ↛ 589line 588 didn't jump to line 589, because the condition on line 588 was never true if origin == afwImage.PARENT and self._xy0 is not None: 

x0, y0 = self._xy0 

colc -= x0 

rowc -= y0 

 

self._impl._pan(colc, rowc) 

 

595 ↛ 596line 595 didn't jump to line 596, because the condition on line 595 was never true if zoomfac is None and rowc is None: 

zoomfac = 2 

 

if zoomfac is not None: 

self._impl._zoom(zoomfac) 

 

def pan(self, colc=None, rowc=None, origin=afwImage.PARENT): 

"""!Pan to (rowc, colc); see also zoom""" 

 

self.zoom(None, colc, rowc, origin) 

 

def interact(self): 

"""!Enter an interactive loop, listening for key presses in display and firing callbacks. 

Exit with q, @c CR, @c ESC, or any other callback function that returns a ``True`` value. 

""" 

interactFinished = False 

 

while not interactFinished: 

ev = self._impl._getEvent() 

614 ↛ 615line 614 didn't jump to line 615, because the condition on line 614 was never true if not ev: 

continue 

k, x, y = ev.k, ev.x, ev.y # for now 

 

618 ↛ 619line 618 didn't jump to line 619, because the condition on line 618 was never true if k not in self._callbacks: 

logger.warn("No callback registered for {0}".format(k)) 

else: 

try: 

interactFinished = self._callbacks[k](k, x, y) 

except Exception as e: 

logger.error( 

"Display._callbacks['{0}']({0},{1},{2}) failed: {3}".format(k, x, y, e)) 

 

def setCallback(self, k, func=None, noRaise=False): 

"""!Set the callback for key k to be func, returning the old callback 

""" 

 

if k in "f": 

632 ↛ 634line 632 didn't jump to line 634, because the condition on line 632 was never false if noRaise: 

return 

raise RuntimeError( 

"Key '%s' is already in use by display, so I can't add a callback for it" % k) 

 

ofunc = self._callbacks.get(k) 

self._callbacks[k] = func if func else noop_callback 

 

self._impl._setCallback(k, self._callbacks[k]) 

 

return ofunc 

 

def getActiveCallbackKeys(self, onlyActive=True): 

"""!Return all callback keys 

@param onlyActive If true only return keys that do something 

""" 

 

return sorted([k for k, func in self._callbacks.items() if 

not (onlyActive and func == noop_callback)]) 

 

# 

# Callbacks for display events 

# 

 

 

class Event: 

"""!A class to handle events such as key presses in image display windows""" 

 

def __init__(self, k, x=float('nan'), y=float('nan')): 

self.k = k 

self.x = x 

self.y = y 

 

def __str__(self): 

return "%s (%.2f, %.2f)" % (self.k, self.x, self.y) 

# 

# Default fallback function 

# 

 

 

def noop_callback(k, x, y): 

"""!Callback function: arguments key, x, y""" 

return False 

 

 

def h_callback(k, x, y): 

print("Enter q or <ESC> to leave interactive mode, h for this help, or a letter to fire a callback") 

return False 

 

# 

# Handle Displays, including the default one (the frame to use when a user specifies None) 

# 

# If the default frame is None, image display is disabled 

# 

 

 

def setDefaultBackend(backend): 

Display.setDefaultBackend(backend) 

 

 

def getDefaultBackend(): 

return Display.getDefaultBackend() 

 

 

def setDefaultFrame(frame=0): 

return Display.setDefaultFrame(frame) 

 

 

def getDefaultFrame(): 

"""Get the default frame for display""" 

return Display.getDefaultFrame() 

 

 

def incrDefaultFrame(): 

"""Increment the default frame for display""" 

return Display.incrDefaultFrame() 

 

 

def setDefaultMaskTransparency(maskPlaneTransparency={}): 

return Display.setDefaultMaskTransparency(maskPlaneTransparency) 

 

 

def setDefaultMaskPlaneColor(name=None, color=None): 

"""!Set the default mapping from mask plane names to colours 

@param name name of mask plane, or a dict mapping names to colours 

@param color Desired color, or None if name is a dict 

 

If name is None, use the hard-coded default dictionary 

""" 

 

return Display.setDefaultMaskPlaneColor(name, color) 

 

 

def getDisplay(frame=None, backend=None, create=True, verbose=False, *args, **kwargs): 

"""!Return the Display indexed by frame, creating it if needs be 

 

See Display.getDisplay 

 

@param frame The desired frame (None => use defaultFrame (see setDefaultFrame)) 

@param backend create the specified frame using this backend (or the default if None) \ 

if it doesn't already exist. If backend == "", it's an error to specify a non-existent frame 

@param create create the display if it doesn't already exist. 

@param verbose Allow backend to be chatty 

@param args arguments passed to Display constructor 

@param kwargs keyword arguments passed to Display constructor 

""" 

 

return Display.getDisplay(frame, backend, create, verbose, *args, **kwargs) 

 

 

def delAllDisplays(): 

"""!Delete and close all known display 

""" 

return Display.delAllDisplays()