ROI.py 70.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# -*- coding: utf-8 -*-
"""
ROI.py -  Interactive graphics items for GraphicsView (ROI widgets)
Copyright 2010  Luke Campagnola
Distributed under MIT/X11 license. See license.txt for more infomation.

Implements a series of graphics items which display movable/scalable/rotatable shapes
for use as region-of-interest markers. ROI class automatically handles extraction 
of array data from ImageItems.

The ROI class is meant to serve as the base for more specific types; see several examples
of how to build an ROI at the bottom of the file.
"""

from pyqtgraph.Qt import QtCore, QtGui
#if not hasattr(QtCore, 'Signal'):
    #QtCore.Signal = QtCore.pyqtSignal
import numpy as np
from numpy.linalg import norm
import scipy.ndimage as ndimage
from pyqtgraph.Point import *
22
from pyqtgraph.SRTTransform import SRTTransform
23
24
25
26
27
28
29
30
from math import cos, sin
import pyqtgraph.functions as fn
from .GraphicsObject import GraphicsObject
from .UIGraphicsItem import UIGraphicsItem

__all__ = [
    'ROI', 
    'TestROI', 'RectROI', 'EllipseROI', 'CircleROI', 'PolygonROI', 
Luke Campagnola's avatar
Luke Campagnola committed
31
    'LineROI', 'MultiLineROI', 'MultiRectROI', 'LineSegmentROI', 'PolyLineROI', 'SpiralROI',
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
]


def rectStr(r):
    return "[%f, %f] + [%f, %f]" % (r.x(), r.y(), r.width(), r.height())

class ROI(GraphicsObject):
    """Generic region-of-interest widget. 
    Can be used for implementing many types of selection box with rotate/translate/scale handles.
    """
    
    sigRegionChangeFinished = QtCore.Signal(object)
    sigRegionChangeStarted = QtCore.Signal(object)
    sigRegionChanged = QtCore.Signal(object)
    sigHoverEvent = QtCore.Signal(object)
47
    sigClicked = QtCore.Signal(object, object)
48
    sigRemoveRequested = QtCore.Signal(object)
49
    
50
    def __init__(self, pos, size=Point(1, 1), angle=0.0, invertible=False, maxBounds=None, snapSize=1.0, scaleSnap=False, translateSnap=False, rotateSnap=False, parent=None, pen=None, movable=True, removable=False):
51
52
        #QObjectWorkaround.__init__(self)
        GraphicsObject.__init__(self, parent)
53
        self.setAcceptedMouseButtons(QtCore.Qt.NoButton)
54
55
56
57
58
        pos = Point(pos)
        size = Point(size)
        self.aspectLocked = False
        self.translatable = movable
        self.rotateAllowed = True
59
60
        self.removable = removable
        self.menu = None
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
        
        self.freeHandleMoved = False ## keep track of whether free handles have moved since last change signal was emitted.
        self.mouseHovering = False
        if pen is None:
            pen = (255, 255, 255)
        self.setPen(pen)
        
        self.handlePen = QtGui.QPen(QtGui.QColor(150, 255, 255))
        self.handles = []
        self.state = {'pos': Point(0,0), 'size': Point(1,1), 'angle': 0}  ## angle is in degrees for ease of Qt integration
        self.lastState = None
        self.setPos(pos)
        self.setAngle(angle)
        self.setSize(size)
        self.setZValue(10)
        self.isMoving = False
        
        self.handleSize = 5
        self.invertible = invertible
        self.maxBounds = maxBounds
        
        self.snapSize = snapSize
        self.translateSnap = translateSnap
        self.rotateSnap = rotateSnap
        self.scaleSnap = scaleSnap
        #self.setFlag(self.ItemIsSelectable, True)
    
    def getState(self):
        return self.stateCopy()

    def stateCopy(self):
        sc = {}
        sc['pos'] = Point(self.state['pos'])
        sc['size'] = Point(self.state['size'])
        sc['angle'] = self.state['angle']
        return sc
        
    def saveState(self):
        """Return the state of the widget in a format suitable for storing to disk. (Points are converted to tuple)"""
        state = {}
        state['pos'] = tuple(self.state['pos'])
        state['size'] = tuple(self.state['size'])
        state['angle'] = self.state['angle']
        return state
    
    def setState(self, state, update=True):
        self.setPos(state['pos'], update=False)
        self.setSize(state['size'], update=False)
        self.setAngle(state['angle'], update=update)
    
    def setZValue(self, z):
        QtGui.QGraphicsItem.setZValue(self, z)
        for h in self.handles:
            h['item'].setZValue(z+1)
        
    def parentBounds(self):
        return self.mapToParent(self.boundingRect()).boundingRect()

    def setPen(self, pen):
        self.pen = fn.mkPen(pen)
        self.currentPen = self.pen
        self.update()
        
    def size(self):
        return self.getState()['size']
        
    def pos(self):
        return self.getState()['pos']
        
    def angle(self):
        return self.getState()['angle']
        
    def setPos(self, pos, update=True, finish=True):
        """Set the position of the ROI (in the parent's coordinate system).
135
        By default, this will cause both sigRegionChanged and sigRegionChangeFinished to be emitted.
136
        
137
        If finish is False, then sigRegionChangeFinished will not be emitted. You can then use 
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
        stateChangeFinished() to cause the signal to be emitted after a series of state changes.
        
        If update is False, the state change will be remembered but not processed and no signals 
        will be emitted. You can then use stateChanged() to complete the state change. This allows
        multiple change functions to be called sequentially while minimizing processing overhead
        and repeated signals. Setting update=False also forces finish=False.
        """
        
        pos = Point(pos)
        self.state['pos'] = pos
        QtGui.QGraphicsItem.setPos(self, pos)
        if update:
            self.stateChanged(finish=finish)
        
    def setSize(self, size, update=True, finish=True):
        """Set the size of the ROI. May be specified as a QPoint, Point, or list of two values.
        See setPos() for an explanation of the update and finish arguments.
        """
        size = Point(size)
        self.prepareGeometryChange()
        self.state['size'] = size
        if update:
            self.stateChanged(finish=finish)
        
    def setAngle(self, angle, update=True, finish=True):
        """Set the angle of rotation (in degrees) for this ROI.
        See setPos() for an explanation of the update and finish arguments.
        """
        self.state['angle'] = angle
        tr = QtGui.QTransform()
        #tr.rotate(-angle * 180 / np.pi)
        tr.rotate(angle)
        self.setTransform(tr)
        if update:
            self.stateChanged(finish=finish)
        
    def scale(self, s, center=[0,0], update=True, finish=True):
        """
        Resize the ROI by scaling relative to *center*.
        See setPos() for an explanation of the *update* and *finish* arguments.
        """
179
        c = self.mapToParent(Point(center) * self.state['size'])
180
181
        self.prepareGeometryChange()
        newSize = self.state['size'] * s
182
        c1 = self.mapToParent(Point(center) * newSize)
183
184
185
        newPos = self.state['pos'] + c - c1
        
        self.setSize(newSize, update=False)
186
        self.setPos(newPos, update=update, finish=finish)
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
        
   
    def translate(self, *args, **kargs):
        """
        Move the ROI to a new position.
        Accepts either (x, y, snap) or ([x,y], snap) as arguments
        If the ROI is bounded and the move would exceed boundaries, then the ROI
        is moved to the nearest acceptable position instead.
        
        snap can be:
           None (default): use self.translateSnap and self.snapSize to determine whether/how to snap
           False:          do not snap
           Point(w,h)      snap to rectangular grid with spacing (w,h)
           True:           snap using self.snapSize (and ignoring self.translateSnap)
           
        Also accepts *update* and *finish* arguments (see setPos() for a description of these).
        """

        if len(args) == 1:
            pt = args[0]
        else:
            pt = args
            
        newState = self.stateCopy()
        newState['pos'] = newState['pos'] + pt
        
        ## snap position
        #snap = kargs.get('snap', None)
        #if (snap is not False)   and   not (snap is None and self.translateSnap is False):
        
        snap = kargs.get('snap', None)
        if snap is None:
            snap = self.translateSnap
        if snap is not False:
            newState['pos'] = self.getSnapPosition(newState['pos'], snap=snap)
        
        #d = ev.scenePos() - self.mapToScene(self.pressPos)
        if self.maxBounds is not None:
            r = self.stateRect(newState)
            #r0 = self.sceneTransform().mapRect(self.boundingRect())
            d = Point(0,0)
            if self.maxBounds.left() > r.left():
                d[0] = self.maxBounds.left() - r.left()
            elif self.maxBounds.right() < r.right():
                d[0] = self.maxBounds.right() - r.right()
            if self.maxBounds.top() > r.top():
                d[1] = self.maxBounds.top() - r.top()
            elif self.maxBounds.bottom() < r.bottom():
                d[1] = self.maxBounds.bottom() - r.bottom()
            newState['pos'] += d
        
        #self.state['pos'] = newState['pos']
        update = kargs.get('update', True)
        finish = kargs.get('finish', True)
        self.setPos(newState['pos'], update=update, finish=finish)
        #if 'update' not in kargs or kargs['update'] is True:
        #self.stateChanged()

    def rotate(self, angle, update=True, finish=True):
        self.setAngle(self.angle()+angle, update=update, finish=finish)

248
249
    def handleMoveStarted(self):
        self.preMoveState = self.getState()
250
    
251
    def addTranslateHandle(self, pos, axes=None, item=None, name=None, index=None):
252
        pos = Point(pos)
253
        return self.addHandle({'name': name, 'type': 't', 'pos': pos, 'item': item}, index=index)
254
    
255
256
257
258
    def addFreeHandle(self, pos=None, axes=None, item=None, name=None, index=None):
        if pos is not None:
            pos = Point(pos)
        return self.addHandle({'name': name, 'type': 'f', 'pos': pos, 'item': item}, index=index)
259
    
260
    def addScaleHandle(self, pos, center, axes=None, item=None, name=None, lockAspect=False, index=None):
261
262
263
264
265
266
267
        pos = Point(pos)
        center = Point(center)
        info = {'name': name, 'type': 's', 'center': center, 'pos': pos, 'item': item, 'lockAspect': lockAspect}
        if pos.x() == center.x():
            info['xoff'] = True
        if pos.y() == center.y():
            info['yoff'] = True
268
        return self.addHandle(info, index=index)
269
    
270
    def addRotateHandle(self, pos, center, item=None, name=None, index=None):
271
272
        pos = Point(pos)
        center = Point(center)
273
        return self.addHandle({'name': name, 'type': 'r', 'center': center, 'pos': pos, 'item': item}, index=index)
274
    
275
    def addScaleRotateHandle(self, pos, center, item=None, name=None, index=None):
276
277
278
279
        pos = Point(pos)
        center = Point(center)
        if pos[0] != center[0] and pos[1] != center[1]:
            raise Exception("Scale/rotate handles must have either the same x or y coordinate as their center point.")
280
        return self.addHandle({'name': name, 'type': 'sr', 'center': center, 'pos': pos, 'item': item}, index=index)
281
    
282
    def addRotateFreeHandle(self, pos, center, axes=None, item=None, name=None, index=None):
283
284
        pos = Point(pos)
        center = Point(center)
285
        return self.addHandle({'name': name, 'type': 'rf', 'center': center, 'pos': pos, 'item': item}, index=index)
286
    
287
288
    def addHandle(self, info, index=None):
        ## If a Handle was not supplied, create it now
289
290
291
292
293
294
        if 'item' not in info or info['item'] is None:
            h = Handle(self.handleSize, typ=info['type'], pen=self.handlePen, parent=self)
            h.setPos(info['pos'] * self.state['size'])
            info['item'] = h
        else:
            h = info['item']
295
296
297
298
299
300
301
302
303
304
305
            if info['pos'] is None:
                info['pos'] = h.pos()
            
        ## connect the handle to this ROI
        #iid = len(self.handles)
        h.connectROI(self)
        if index is None:
            self.handles.append(info)
        else:
            self.handles.insert(index, info)
        
306
        h.setZValue(self.zValue()+1)
307
        self.stateChanged()
308
309
        return h
    
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
    def indexOfHandle(self, handle):
        if isinstance(handle, Handle):
            index = [i for i, info in enumerate(self.handles) if info['item'] is handle]    
            if len(index) == 0:
                raise Exception("Cannot remove handle; it is not attached to this ROI")
            return index[0]
        else:
            return handle
        
    def removeHandle(self, handle):
        """Remove a handle from this ROI. Argument may be either a Handle instance or the integer index of the handle."""
        index = self.indexOfHandle(handle)
            
        handle = self.handles[index]['item']
        self.handles.pop(index)
        handle.disconnectROI(self)
        if len(handle.rois) == 0:
            self.scene().removeItem(handle)
        self.stateChanged()
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
    def replaceHandle(self, oldHandle, newHandle):
        """Replace one handle in the ROI for another. This is useful when connecting multiple ROIs together.
        *oldHandle* may be a Handle instance or the index of a handle."""
        #print "========================="
        #print "replace", oldHandle, newHandle
        #print self
        #print self.handles
        #print "-----------------"
        index = self.indexOfHandle(oldHandle)
        info = self.handles[index]
        self.removeHandle(index)
        info['item'] = newHandle
        info['pos'] = newHandle.pos()
        self.addHandle(info, index=index)
        #print self.handles
        
    def checkRemoveHandle(self, handle):
        ## This is used when displaying a Handle's context menu to determine
        ## whether removing is allowed. 
        ## Subclasses may wish to override this to disable the menu entry.
        ## Note: by default, handles are not user-removable even if this method returns True.
        return True
        
        
354
355
356
357
358
359
360
361
362
363
    def getLocalHandlePositions(self, index=None):
        """Returns the position of a handle in ROI coordinates"""
        if index == None:
            positions = []
            for h in self.handles:
                positions.append((h['name'], h['pos']))
            return positions
        else:
            return (self.handles[index]['name'], self.handles[index]['pos'])
            
364
    def getSceneHandlePositions(self, index=None):
365
366
367
368
369
370
371
372
        if index == None:
            positions = []
            for h in self.handles:
                positions.append((h['name'], h['item'].scenePos()))
            return positions
        else:
            return (self.handles[index]['name'], self.handles[index]['item'].scenePos())
        
Luke Campagnola's avatar
Luke Campagnola committed
373
374
375
    def getHandles(self):
        return [h['item'] for h in self.handles]
    
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
    def mapSceneToParent(self, pt):
        return self.mapToParent(self.mapFromScene(pt))

    def setSelected(self, s):
        QtGui.QGraphicsItem.setSelected(self, s)
        #print "select", self, s
        if s:
            for h in self.handles:
                h['item'].show()
        else:
            for h in self.handles:
                h['item'].hide()


    def hoverEvent(self, ev):
391
392
393
394
        hover = False
        if not ev.isExit():
            if self.translatable and ev.acceptDrags(QtCore.Qt.LeftButton):
                hover=True
395
                
396
397
398
            for btn in [QtCore.Qt.LeftButton, QtCore.Qt.RightButton, QtCore.Qt.MidButton]:
                if int(self.acceptedMouseButtons() & btn) > 0 and ev.acceptClicks(btn):
                    hover=True
399
400
401
            if self.contextMenuEnabled():
                ev.acceptClicks(QtCore.Qt.RightButton)
                
402
        if hover:
403
404
            self.setMouseHover(True)
            self.sigHoverEvent.emit(self)
405
406
407
            ev.acceptClicks(QtCore.Qt.LeftButton)  ## If the ROI is hilighted, we should accept all clicks to avoid confusion.
            ev.acceptClicks(QtCore.Qt.RightButton)
            ev.acceptClicks(QtCore.Qt.MidButton)
408
409
410
411
412
413
414
415
416
417
418
419
420
        else:
            self.setMouseHover(False)

    def setMouseHover(self, hover):
        ## Inform the ROI that the mouse is(not) hovering over it
        if self.mouseHovering == hover:
            return
        self.mouseHovering = hover
        if hover:
            self.currentPen = fn.mkPen(255, 255, 0)
        else:
            self.currentPen = self.pen
        self.update()
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

    def contextMenuEnabled(self):
        return self.removable
    
    def raiseContextMenu(self, ev):
        if not self.contextMenuEnabled():
            return
        menu = self.getMenu()
        menu = self.scene().addParentContextMenus(self, menu, ev)
        pos = ev.screenPos()
        menu.popup(QtCore.QPoint(pos.x(), pos.y()))

    def getMenu(self):
        if self.menu is None:
            self.menu = QtGui.QMenu()
            self.menu.setTitle("ROI")
            remAct = QtGui.QAction("Remove ROI", self.menu)
            remAct.triggered.connect(self.removeClicked)
            self.menu.addAction(remAct)
            self.menu.remAct = remAct
        return self.menu

    def removeClicked(self):
        ## Send remove event only after we have exited the menu event handler
        self.removeTimer = QtCore.QTimer()
        self.removeTimer.timeout.connect(lambda: self.sigRemoveRequested.emit(self))
        self.removeTimer.start(0)
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
    def mouseDragEvent(self, ev):
        if ev.isStart():
            #p = ev.pos()
            #if not self.isMoving and not self.shape().contains(p):
                #ev.ignore()
                #return        
            if ev.button() == QtCore.Qt.LeftButton:
                self.setSelected(True)
                if self.translatable:
                    self.isMoving = True
                    self.preMoveState = self.getState()
                    self.cursorOffset = self.pos() - self.mapToParent(ev.buttonDownPos())
                    self.sigRegionChangeStarted.emit(self)
                    ev.accept()
                else:
                    ev.ignore()

        elif ev.isFinish():
            if self.translatable:
                if self.isMoving:
                    self.stateChangeFinished()
                self.isMoving = False
            return

        if self.translatable and self.isMoving and ev.buttons() == QtCore.Qt.LeftButton:
            snap = True if (ev.modifiers() & QtCore.Qt.ControlModifier) else None
            newPos = self.mapToParent(ev.pos()) + self.cursorOffset
            self.translate(newPos - self.pos(), snap=snap, finish=False)
        
    def mouseClickEvent(self, ev):
481
482
483
        if ev.button() == QtCore.Qt.RightButton and self.isMoving:
            ev.accept()
            self.cancelMove()
484
485
486
        if ev.button() == QtCore.Qt.RightButton and self.contextMenuEnabled():
            self.raiseContextMenu(ev)
            ev.accept()
487
488
489
490
491
492
493
494
        elif int(ev.button() & self.acceptedMouseButtons()) > 0:
            ev.accept()
            self.sigClicked.emit(self, ev)
        else:
            ev.ignore()
            
        
            
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

    def cancelMove(self):
        self.isMoving = False
        self.setState(self.preMoveState)


    #def pointDragEvent(self, pt, ev):
        ### just for handling drag start/stop.
        ### drag moves are handled through movePoint()
        
        #if ev.isStart():
            #self.isMoving = True
            #self.preMoveState = self.getState()
            
            #self.sigRegionChangeStarted.emit(self)
        #elif ev.isFinish():
            #self.isMoving = False
            #self.sigRegionChangeFinished.emit(self)
            #return
        
        
    #def pointPressEvent(self, pt, ev):
        ##print "press"
        #self.isMoving = True
        #self.preMoveState = self.getState()
        
        ##self.emit(QtCore.SIGNAL('regionChangeStarted'), self)
        #self.sigRegionChangeStarted.emit(self)
        ##self.pressPos = self.mapFromScene(ev.scenePos())
        ##self.pressHandlePos = self.handles[pt]['item'].pos()
    
    #def pointReleaseEvent(self, pt, ev):
        ##print "release"
        #self.isMoving = False
        ##self.emit(QtCore.SIGNAL('regionChangeFinished'), self)
        #self.sigRegionChangeFinished.emit(self)
    
    #def pointMoveEvent(self, pt, ev):
        #self.movePoint(pt, ev.scenePos(), ev.modifiers())
        
    
536
    def checkPointMove(self, handle, pos, modifiers):
537
538
539
540
541
542
        """When handles move, they must ask the ROI if the move is acceptable.
        By default, this always returns True. Subclasses may wish override.
        """
        return True
    

Luke Campagnola's avatar
Luke Campagnola committed
543
    def movePoint(self, handle, pos, modifiers=QtCore.Qt.KeyboardModifier(), finish=True, coords='parent'):
544
545
546
547
        ## called by Handles when they are moved. 
        ## pos is the new position of the handle in scene coords, as requested by the handle.
        
        newState = self.stateCopy()
548
549
        index = self.indexOfHandle(handle)
        h = self.handles[index]
Luke Campagnola's avatar
Luke Campagnola committed
550
        p0 = self.mapToParent(h['pos'] * self.state['size'])
551
552
        p1 = Point(pos)
        
Luke Campagnola's avatar
Luke Campagnola committed
553
554
555
556
557
558
559
560
        if coords == 'parent':
            pass
        elif coords == 'scene':
            p1 = self.mapSceneToParent(p1)
        else:
            raise Exception("New point location must be given in either 'parent' or 'scene' coordinates.")

        
561
        ## transform p0 and p1 into parent's coordinates (same as scene coords if there is no parent). I forget why.
Luke Campagnola's avatar
Luke Campagnola committed
562
563
        #p0 = self.mapSceneToParent(p0)
        #p1 = self.mapSceneToParent(p1)
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578

        ## Handles with a 'center' need to know their local position relative to the center point (lp0, lp1)
        if 'center' in h:
            c = h['center']
            cs = c * self.state['size']
            lp0 = self.mapFromParent(p0) - cs
            lp1 = self.mapFromParent(p1) - cs
        
        if h['type'] == 't':
            snap = True if (modifiers & QtCore.Qt.ControlModifier) else None
            #if self.translateSnap or ():
                #snap = Point(self.snapSize, self.snapSize)
            self.translate(p1-p0, snap=snap, update=False)
        
        elif h['type'] == 'f':
Luke Campagnola's avatar
Luke Campagnola committed
579
580
            newPos = self.mapFromParent(p1)
            h['item'].setPos(newPos)
581
            h['pos'] = newPos
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
            self.freeHandleMoved = True
            #self.sigRegionChanged.emit(self)  ## should be taken care of by call to stateChanged()
            
        elif h['type'] == 's':
            ## If a handle and its center have the same x or y value, we can't scale across that axis.
            if h['center'][0] == h['pos'][0]:
                lp1[0] = 0
            if h['center'][1] == h['pos'][1]:
                lp1[1] = 0
            
            ## snap 
            if self.scaleSnap or (modifiers & QtCore.Qt.ControlModifier):
                lp1[0] = round(lp1[0] / self.snapSize) * self.snapSize
                lp1[1] = round(lp1[1] / self.snapSize) * self.snapSize
                
            ## preserve aspect ratio (this can override snapping)
            if h['lockAspect'] or (modifiers & QtCore.Qt.AltModifier):
                #arv = Point(self.preMoveState['size']) - 
                lp1 = lp1.proj(lp0)
            
            ## determine scale factors and new size of ROI
            hs = h['pos'] - c
            if hs[0] == 0:
                hs[0] = 1
            if hs[1] == 0:
                hs[1] = 1
            newSize = lp1 / hs
            
            ## Perform some corrections and limit checks
            if newSize[0] == 0:
                newSize[0] = newState['size'][0]
            if newSize[1] == 0:
                newSize[1] = newState['size'][1]
            if not self.invertible:
                if newSize[0] < 0:
                    newSize[0] = newState['size'][0]
                if newSize[1] < 0:
                    newSize[1] = newState['size'][1]
            if self.aspectLocked:
                newSize[0] = newSize[1]
            
            ## Move ROI so the center point occupies the same scene location after the scale
            s0 = c * self.state['size']
            s1 = c * newSize
            cc = self.mapToParent(s0 - s1) - self.mapToParent(Point(0, 0))
            
            ## update state, do more boundary checks
            newState['size'] = newSize
            newState['pos'] = newState['pos'] + cc
            if self.maxBounds is not None:
                r = self.stateRect(newState)
                if not self.maxBounds.contains(r):
                    return
            
            self.setPos(newState['pos'], update=False)
            self.setSize(newState['size'], update=False)
        
        elif h['type'] in ['r', 'rf']:
            if h['type'] == 'rf':
                self.freeHandleMoved = True
            
            if not self.rotateAllowed:
                return
            ## If the handle is directly over its center point, we can't compute an angle.
            if lp1.length() == 0 or lp0.length() == 0:
                return
            
            ## determine new rotation angle, constrained if necessary
            ang = newState['angle'] - lp0.angle(lp1)
            if ang is None:  ## this should never happen..
                return
            if self.rotateSnap or (modifiers & QtCore.Qt.ControlModifier):
                ang = round(ang / 15.) * 15.  ## 180/12 = 15
            
            ## create rotation transform
            tr = QtGui.QTransform()
            tr.rotate(ang)
            
            ## move ROI so that center point remains stationary after rotate
            cc = self.mapToParent(cs) - (tr.map(cs) + self.state['pos'])
            newState['angle'] = ang
            newState['pos'] = newState['pos'] + cc
            
            ## check boundaries, update
            if self.maxBounds is not None:
                r = self.stateRect(newState)
                if not self.maxBounds.contains(r):
                    return
            #self.setTransform(tr)
            self.setPos(newState['pos'], update=False)
            self.setAngle(ang, update=False)
            #self.state = newState
            
            ## If this is a free-rotate handle, its distance from the center may change.
            
            if h['type'] == 'rf':
                h['item'].setPos(self.mapFromScene(p1))  ## changes ROI coordinates of handle
                
        elif h['type'] == 'sr':
            if h['center'][0] == h['pos'][0]:
                scaleAxis = 1
            else:
                scaleAxis = 0
            
            if lp1.length() == 0 or lp0.length() == 0:
                return
            
            ang = newState['angle'] - lp0.angle(lp1)
            if ang is None:
                return
            if self.rotateSnap or (modifiers & QtCore.Qt.ControlModifier):
                #ang = round(ang / (np.pi/12.)) * (np.pi/12.)
                ang = round(ang / 15.) * 15.
            
            hs = abs(h['pos'][scaleAxis] - c[scaleAxis])
            newState['size'][scaleAxis] = lp1.length() / hs
            #if self.scaleSnap or (modifiers & QtCore.Qt.ControlModifier):
            if self.scaleSnap:  ## use CTRL only for angular snap here.
                newState['size'][scaleAxis] = round(newState['size'][scaleAxis] / self.snapSize) * self.snapSize
            if newState['size'][scaleAxis] == 0:
                newState['size'][scaleAxis] = 1
                
            c1 = c * newState['size']
            tr = QtGui.QTransform()
            tr.rotate(ang)
            
            cc = self.mapToParent(cs) - (tr.map(c1) + self.state['pos'])
            newState['angle'] = ang
            newState['pos'] = newState['pos'] + cc
            if self.maxBounds is not None:
                r = self.stateRect(newState)
                if not self.maxBounds.contains(r):
                    return
            #self.setTransform(tr)
            #self.setPos(newState['pos'], update=False)
            #self.prepareGeometryChange()
            #self.state = newState
            self.setState(newState, update=False)
        
        self.stateChanged(finish=finish)
    
    def stateChanged(self, finish=True):
        """Process changes to the state of the ROI.
        If there are any changes, then the positions of handles are updated accordingly
        and sigRegionChanged is emitted. If finish is True, then 
        sigRegionChangeFinished will also be emitted."""
        
        changed = False
        if self.lastState is None:
            changed = True
        else:
            for k in list(self.state.keys()):
                if self.state[k] != self.lastState[k]:
                    changed = True
736
        
737
        self.prepareGeometryChange()
738
739
740
741
742
743
        if changed:
            ## Move all handles to match the current configuration of the ROI
            for h in self.handles:
                if h['item'] in self.childItems():
                    p = h['pos']
                    h['item'].setPos(h['pos'] * self.state['size'])
744
745
746
                #else:
                #    trans = self.state['pos']-self.lastState['pos']
                #    h['item'].setPos(h['pos'] + h['item'].parentItem().mapFromParent(trans))
747
748
749
750
751
752
753
                    
            self.update()
            self.sigRegionChanged.emit(self)
        elif self.freeHandleMoved:
            self.sigRegionChanged.emit(self)
            
        self.freeHandleMoved = False
754
        self.lastState = self.stateCopy()
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
            
        if finish:
            self.stateChangeFinished()
    
    def stateChangeFinished(self):
        self.sigRegionChangeFinished.emit(self)
    
    def stateRect(self, state):
        r = QtCore.QRectF(0, 0, state['size'][0], state['size'][1])
        tr = QtGui.QTransform()
        #tr.rotate(-state['angle'] * 180 / np.pi)
        tr.rotate(-state['angle'])
        r = tr.mapRect(r)
        return r.adjusted(state['pos'][0], state['pos'][1], state['pos'][0], state['pos'][1])
    
    
    def getSnapPosition(self, pos, snap=None):
        ## Given that pos has been requested, return the nearest snap-to position
        ## optionally, snap may be passed in to specify a rectangular snap grid.
        ## override this function for more interesting snap functionality..
        
        if snap is None or snap is True:
            if self.snapSize is None:
                return pos
            snap = Point(self.snapSize, self.snapSize)
        
        return Point(
            round(pos[0] / snap[0]) * snap[0],
            round(pos[1] / snap[1]) * snap[1]
        )
    
    
    def boundingRect(self):
        return QtCore.QRectF(0, 0, self.state['size'][0], self.state['size'][1]).normalized()

    def paint(self, p, opt, widget):
        p.save()
        r = self.boundingRect()
        p.setRenderHint(QtGui.QPainter.Antialiasing)
        p.setPen(self.currentPen)
        p.translate(r.left(), r.top())
        p.scale(r.width(), r.height())
        p.drawRect(0, 0, 1, 1)
        p.restore()

    def getArraySlice(self, data, img, axes=(0,1), returnSlice=True):
        """Return a tuple of slice objects that can be used to slice the region from data covered by this ROI.
        Also returns the transform which maps the ROI into data coordinates.
        
        If returnSlice is set to False, the function returns a pair of tuples with the values that would have 
        been used to generate the slice objects. ((ax0Start, ax0Stop), (ax1Start, ax1Stop))"""
        #print "getArraySlice"
        
        ## Determine shape of array along ROI axes
        dShape = (data.shape[axes[0]], data.shape[axes[1]])
        #print "  dshape", dShape
        
        ## Determine transform that maps ROI bounding box to image coordinates
Luke Campagnola's avatar
Luke Campagnola committed
813
        tr = self.sceneTransform() * fn.invertQTransform(img.sceneTransform())
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
        
        ## Modify transform to scale from image coords to data coords
        #m = QtGui.QTransform()
        tr.scale(float(dShape[0]) / img.width(), float(dShape[1]) / img.height())
        #tr = tr * m
        
        ## Transform ROI bounds into data bounds
        dataBounds = tr.mapRect(self.boundingRect())
        #print "  boundingRect:", self.boundingRect()
        #print "  dataBounds:", dataBounds
        
        ## Intersect transformed ROI bounds with data bounds
        intBounds = dataBounds.intersect(QtCore.QRectF(0, 0, dShape[0], dShape[1]))
        #print "  intBounds:", intBounds
        
        ## Determine index values to use when referencing the array. 
        bounds = (
            (int(min(intBounds.left(), intBounds.right())), int(1+max(intBounds.left(), intBounds.right()))),
            (int(min(intBounds.bottom(), intBounds.top())), int(1+max(intBounds.bottom(), intBounds.top())))
        )
        #print "  bounds:", bounds
        
        if returnSlice:
            ## Create slice objects
            sl = [slice(None)] * data.ndim
            sl[axes[0]] = slice(*bounds[0])
            sl[axes[1]] = slice(*bounds[1])
            return tuple(sl), tr
        else:
            return bounds, tr

845
846
    def getArrayRegion(self, data, img, axes=(0,1), returnMappedCoords=False, **kwds):
        """Use the position and orientation of this ROI relative to an imageItem to pull a slice from an array.
847
        
848
849
850
        This method uses :func:`affineSlice <pyqtgraph.affineSlice>` to generate
        the slice from *data* and uses :func:`getAffineSliceParams <pyqtgraph.ROI.getAffineSliceParams>` to determine the parameters to 
        pass to :func:`affineSlice <pyqtgraph.affineSlice>`.
851
        
852
853
854
855
856
        If *returnMappedCoords* is True, then the method returns a tuple (result, coords) 
        such that coords is the set of coordinates used to interpolate values from the original
        data, mapped into the parent coordinate system of the image. This is useful, when slicing
        data from images that have been transformed, for determining the location of each value
        in the sliced data.
857
        
858
859
        All extra keyword arguments are passed to :func:`affineSlice <pyqtgraph.affineSlice>`.
        """
860
        
861
862
863
864
865
866
        shape, vectors, origin = self.getAffineSliceParams(data, img, axes)
        if not returnMappedCoords:
            return fn.affineSlice(data, shape=shape, vectors=vectors, origin=origin, axes=axes, **kwds)
        else:
            kwds['returnCoords'] = True
            result, coords = fn.affineSlice(data, shape=shape, vectors=vectors, origin=origin, axes=axes, **kwds)
867
868
869
870
871
872
873
874
875
876
877
878
            #tr = fn.transformToArray(img.transform())[:2]  ## remove perspective transform values
            
            ### separate translation from scale/rotate
            #translate = tr[:,2]
            #tr = tr[:,:2]
            #tr = tr.reshape((2,2) + (1,)*(coords.ndim-1))
            #coords = coords[np.newaxis, ...]
            
            ### map coordinates and return
            #mapped = (tr*coords).sum(axis=0)  ## apply scale/rotate
            #mapped += translate.reshape((2,1,1))
            mapped = fn.transformCoordinates(img.transform(), coords)
879
880
881
            return result, mapped
            
            
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
        ### transpose data so x and y are the first 2 axes
        #trAx = range(0, data.ndim)
        #trAx.remove(axes[0])
        #trAx.remove(axes[1])
        #tr1 = tuple(axes) + tuple(trAx)
        #arr = data.transpose(tr1)
        
        ### Determine the minimal area of the data we will need
        #(dataBounds, roiDataTransform) = self.getArraySlice(data, img, returnSlice=False, axes=axes)

        ### Pad data boundaries by 1px if possible
        #dataBounds = (
            #(max(dataBounds[0][0]-1, 0), min(dataBounds[0][1]+1, arr.shape[0])),
            #(max(dataBounds[1][0]-1, 0), min(dataBounds[1][1]+1, arr.shape[1]))
        #)

        ### Extract minimal data from array
        #arr1 = arr[dataBounds[0][0]:dataBounds[0][1], dataBounds[1][0]:dataBounds[1][1]]
        
        ### Update roiDataTransform to reflect this extraction
        #roiDataTransform *= QtGui.QTransform().translate(-dataBounds[0][0], -dataBounds[1][0]) 
        #### (roiDataTransform now maps from ROI coords to extracted data coords)
        
        
        ### Rotate array
        #if abs(self.state['angle']) > 1e-5:
            #arr2 = ndimage.rotate(arr1, self.state['angle'] * 180 / np.pi, order=1)
            
            ### update data transforms to reflect this rotation
            #rot = QtGui.QTransform().rotate(self.state['angle'] * 180 / np.pi)
            #roiDataTransform *= rot
            
            ### The rotation also causes a shift which must be accounted for:
            #dataBound = QtCore.QRectF(0, 0, arr1.shape[0], arr1.shape[1])
            #rotBound = rot.mapRect(dataBound)
            #roiDataTransform *= QtGui.QTransform().translate(-rotBound.left(), -rotBound.top())
            
        #else:
            #arr2 = arr1
        
        
        
        #### Shift off partial pixels
        ## 1. map ROI into current data space
        #roiBounds = roiDataTransform.mapRect(self.boundingRect())
        
        ## 2. Determine amount to shift data
        #shift = (int(roiBounds.left()) - roiBounds.left(), int(roiBounds.bottom()) - roiBounds.bottom())
        #if abs(shift[0]) > 1e-6 or abs(shift[1]) > 1e-6:
            ## 3. pad array with 0s before shifting
            #arr2a = np.zeros((arr2.shape[0]+2, arr2.shape[1]+2) + arr2.shape[2:], dtype=arr2.dtype)
            #arr2a[1:-1, 1:-1] = arr2
            
            ## 4. shift array and udpate transforms
            #arr3 = ndimage.shift(arr2a, shift + (0,)*(arr2.ndim-2), order=1)
            #roiDataTransform *= QtGui.QTransform().translate(1+shift[0], 1+shift[1]) 
        #else:
            #arr3 = arr2
        
        
        #### Extract needed region from rotated/shifted array
        ## 1. map ROI into current data space (round these values off--they should be exact integer values at this point)
        #roiBounds = roiDataTransform.mapRect(self.boundingRect())
        ##print self, roiBounds.height()
        ##import traceback
        ##traceback.print_stack()
        
        #roiBounds = QtCore.QRect(round(roiBounds.left()), round(roiBounds.top()), round(roiBounds.width()), round(roiBounds.height()))
        
        ##2. intersect ROI with data bounds
        #dataBounds = roiBounds.intersect(QtCore.QRect(0, 0, arr3.shape[0], arr3.shape[1]))
        
        ##3. Extract data from array
        #db = dataBounds
        #bounds = (
            #(db.left(), db.right()+1),
            #(db.top(), db.bottom()+1)
        #)
        #arr4 = arr3[bounds[0][0]:bounds[0][1], bounds[1][0]:bounds[1][1]]

        #### Create zero array in size of ROI
        #arr5 = np.zeros((roiBounds.width(), roiBounds.height()) + arr4.shape[2:], dtype=arr4.dtype)
        
        ### Fill array with ROI data
        #orig = Point(dataBounds.topLeft() - roiBounds.topLeft())
        #subArr = arr5[orig[0]:orig[0]+arr4.shape[0], orig[1]:orig[1]+arr4.shape[1]]
        #subArr[:] = arr4[:subArr.shape[0], :subArr.shape[1]]
        
        
        ### figure out the reverse transpose order
        #tr2 = np.array(tr1)
        #for i in range(0, len(tr2)):
            #tr2[tr1[i]] = i
        #tr2 = tuple(tr2)
        
        ### Untranspose array before returning
        #return arr5.transpose(tr2)

Luke Campagnola's avatar
Luke Campagnola committed
980
    def getAffineSliceParams(self, data, img, axes=(0,1)):
981
982
983
984
985
986
        """
        Returns the parameters needed to use :func:`affineSlice <pyqtgraph.affineSlice>` to 
        extract a subset of *data* using this ROI and *img* to specify the subset.
        
        See :func:`getArrayRegion <pyqtgraph.ROI.getArrayRegion>` for more information.
        """
Luke Campagnola's avatar
Luke Campagnola committed
987
988
        if self.scene() is not img.scene():
            raise Exception("ROI and target item must be members of the same scene.")
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
        
        shape = self.state['size']
        
        origin = self.mapToItem(img, QtCore.QPointF(0, 0))
        
        ## vx and vy point in the directions of the slice axes, but must be scaled properly
        vx = self.mapToItem(img, QtCore.QPointF(1, 0)) - origin
        vy = self.mapToItem(img, QtCore.QPointF(0, 1)) - origin
        
        lvx = np.sqrt(vx.x()**2 + vx.y()**2)
        lvy = np.sqrt(vy.x()**2 + vy.y()**2)
        pxLen = img.width() / float(data.shape[axes[0]])
        #img.width is number of pixels or width of item?
        #need pxWidth and pxHeight instead of pxLen ?
        sx =  pxLen / lvx
        sy =  pxLen / lvy
        
        vectors = ((vx.x()*sx, vx.y()*sx), (vy.x()*sy, vy.y()*sy))
        shape = self.state['size']
        shape = [abs(shape[0]/sx), abs(shape[1]/sy)]
        
        origin = (origin.x(), origin.y())
        return shape, vectors, origin
        
1013
    def getGlobalTransform(self, relativeTo=None):
1014
1015
        """Return global transformation (rotation angle+translation) required to move 
        from relative state to current state. If relative state isn't specified,
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
        then we use the state of the ROI when mouse is pressed."""
        if relativeTo == None:
            relativeTo = self.preMoveState
        st = self.getState()
        
        ## this is only allowed because we will be comparing the two 
        relativeTo['scale'] = relativeTo['size']
        st['scale'] = st['size']
        
        
        
1027
1028
        t1 = SRTTransform(relativeTo)
        t2 = SRTTransform(st)
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
        return t2/t1
        
        
        #st = self.getState()
        
        ### rotation
        #ang = (st['angle']-relativeTo['angle']) * 180. / 3.14159265358
        #rot = QtGui.QTransform()
        #rot.rotate(-ang)

        ### We need to come up with a universal transformation--one that can be applied to other objects 
        ### such that all maintain alignment. 
        ### More specifically, we need to turn the ROI's position and angle into
        ### a rotation _around the origin_ and a translation.
        
        #p0 = Point(relativeTo['pos'])

        ### base position, rotated
        #p1 = rot.map(p0)
        
        #trans = Point(st['pos']) - p1
        #return trans, ang

    def applyGlobalTransform(self, tr):
        st = self.getState()
        
        st['scale'] = st['size']
1056
        st = SRTTransform(st)
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
        st = (st * tr).saveState()
        st['size'] = st['scale']
        self.setState(st)


class Handle(UIGraphicsItem):
    
    types = {   ## defines number of sides, start angle for each handle type
        't': (4, np.pi/4),
        'f': (4, np.pi/4), 
        's': (4, 0),
        'r': (12, 0),
        'sr': (12, 0),
        'rf': (12, 0),
    }
1072
1073
1074

    sigClicked = QtCore.Signal(object, object)   # self, event
    sigRemoveRequested = QtCore.Signal(object)   # self
1075
    
1076
    def __init__(self, radius, typ=None, pen=(200, 200, 220), parent=None, deletable=False):
1077
1078
1079
        #print "   create item with parent", parent
        #self.bounds = QtCore.QRectF(-1e-10, -1e-10, 2e-10, 2e-10)
        #self.setFlags(self.ItemIgnoresTransformations | self.ItemSendsScenePositionChanges)
1080
        self.rois = []
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
        self.radius = radius
        self.typ = typ
        self.pen = fn.mkPen(pen)
        self.currentPen = self.pen
        self.pen.setWidth(0)
        self.pen.setCosmetic(True)
        self.isMoving = False
        self.sides, self.startAng = self.types[typ]
        self.buildPath()
        self._shape = None
1091
        self.menu = self.buildMenu()
1092
1093
        
        UIGraphicsItem.__init__(self, parent=parent)
1094
1095
1096
1097
        self.setAcceptedMouseButtons(QtCore.Qt.NoButton)
        self.deletable = deletable
        if deletable:
            self.setAcceptedMouseButtons(QtCore.Qt.RightButton)        
1098
1099
1100
        #self.updateShape()
        self.setZValue(11)
            
1101
    def connectROI(self, roi):
1102
        ### roi is the "parent" roi, i is the index of the handle in roi.handles
1103
        self.rois.append(roi)
1104
1105
        
    def disconnectROI(self, roi):
1106
1107
1108
1109
        self.rois.remove(roi)
        #for i, r in enumerate(self.roi):
            #if r[0] == roi:
                #self.roi.pop(i)
1110
                
1111
1112
1113
    #def close(self):
        #for r in self.roi:
            #r.removeHandle(self)
1114
1115
1116
1117
1118
1119
1120
            
    def setDeletable(self, b):
        self.deletable = b
        if b:
            self.setAcceptedMouseButtons(self.acceptedMouseButtons() | QtCore.Qt.RightButton)
        else:
            self.setAcceptedMouseButtons(self.acceptedMouseButtons() & ~QtCore.Qt.RightButton)
1121
1122
1123
            
    def removeClicked(self):
        self.sigRemoveRequested.emit(self)
1124
1125

    def hoverEvent(self, ev):
1126
1127
1128
1129
1130
1131
1132
1133
1134
        hover = False
        if not ev.isExit():
            if ev.acceptDrags(QtCore.Qt.LeftButton):
                hover=True
            for btn in [QtCore.Qt.LeftButton, QtCore.Qt.RightButton, QtCore.Qt.MidButton]:
                if int(self.acceptedMouseButtons() & btn) > 0 and ev.acceptClicks(btn):
                    hover=True
                    
        if hover:
1135
1136
1137
1138
            self.currentPen = fn.mkPen(255, 255,0)
        else:
            self.currentPen = self.pen
        self.update()
1139
1140
1141
1142
1143
        #if (not ev.isExit()) and ev.acceptDrags(QtCore.Qt.LeftButton):
            #self.currentPen = fn.mkPen(255, 255,0)
        #else:
            #self.currentPen = self.pen
        #self.update()
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
            


    def mouseClickEvent(self, ev):
        ## right-click cancels drag
        if ev.button() == QtCore.Qt.RightButton and self.isMoving:
            self.isMoving = False  ## prevents any further motion
            self.movePoint(self.startPos, finish=True)
            #for r in self.roi:
                #r[0].cancelMove()
            ev.accept()
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
        elif int(ev.button() & self.acceptedMouseButtons()) > 0:
            ev.accept()
            if ev.button() == QtCore.Qt.RightButton and self.deletable:
                self.raiseContextMenu(ev)
            self.sigClicked.emit(self, ev)
        else:
            ev.ignore()        
            
            #elif self.deletable:
                #ev.accept()
                #self.raiseContextMenu(ev)
            #else:
                #ev.ignore()
                
    def buildMenu(self):
        menu = QtGui.QMenu()
        menu.setTitle("Handle")
1172
        self.removeAction = menu.addAction("Remove handle", self.removeClicked) 
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
        return menu
        
    def getMenu(self):
        return self.menu
                
            
    def getContextMenus(self, event):
        return [self.menu]
    
    def raiseContextMenu(self, ev):
        menu = self.scene().addParentContextMenus(self, self.getMenu(), ev)
1184
1185
1186
1187
        
        ## Make sure it is still ok to remove this handle
        removeAllowed = all([r.checkRemoveHandle(self) for r in self.rois])
        self.removeAction.setEnabled(removeAllowed)
1188
1189
        pos = ev.screenPos()
        menu.popup(QtCore.QPoint(pos.x(), pos.y()))    
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203

    def mouseDragEvent(self, ev):
        if ev.button() != QtCore.Qt.LeftButton:
            return
        ev.accept()
        
        ## Inform ROIs that a drag is happening 
        ##  note: the ROI is informed that the handle has moved using ROI.movePoint
        ##  this is for other (more nefarious) purposes.
        #for r in self.roi:
            #r[0].pointDragEvent(r[1], ev)
            
        if ev.isFinish():
            if self.isMoving:
1204
1205
                for r in self.rois:
                    r.stateChangeFinished()
1206
1207
            self.isMoving = False
        elif ev.isStart():
1208
1209
            for r in self.rois:
                r.handleMoveStarted()
1210
1211
1212
1213
1214
1215
1216
1217
1218
            self.isMoving = True
            self.startPos = self.scenePos()
            self.cursorOffset = self.scenePos() - ev.buttonDownScenePos()
            
        if self.isMoving:  ## note: isMoving may become False in mid-drag due to right-click.
            pos = ev.scenePos() + self.cursorOffset
            self.movePoint(pos, ev.modifiers(), finish=False)

    def movePoint(self, pos, modifiers=QtCore.Qt.KeyboardModifier(), finish=True):
1219
1220
        for r in self.rois:
            if not r.checkPointMove(self, pos, modifiers):
1221
1222
1223
                return
        #print "point moved; inform %d ROIs" % len(self.roi)
        # A handle can be used by multiple ROIs; tell each to update its handle position
1224
        for r in self.rois:
Luke Campagnola's avatar
Luke Campagnola committed
1225
            r.movePoint(self, pos, modifiers, finish=finish, coords='scene')
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
        
    def buildPath(self):
        size = self.radius
        self.path = QtGui.QPainterPath()
        ang = self.startAng
        dt = 2*np.pi / self.sides
        for i in range(0, self.sides+1):
            x = size * cos(ang)
            y = size * sin(ang)
            ang += dt
            if i == 0:
                self.path.moveTo(x, y)
            else:
                self.path.lineTo(x, y)            
            
    def paint(self, p, opt, widget):
        ### determine rotation of transform
        #m = self.sceneTransform()
        ##mi = m.inverted()[0]
        #v = m.map(QtCore.QPointF(1, 0)) - m.map(QtCore.QPointF(0, 0))
        #va = np.arctan2(v.y(), v.x())
        
        ### Determine length of unit vector in painter's coords
        ##size = mi.map(Point(self.radius, self.radius)) - mi.map(Point(0, 0))
        ##size = (size.x()*size.x() + size.y() * size.y()) ** 0.5
        #size = self.radius
        
        #bounds = QtCore.QRectF(-size, -size, size*2, size*2)
        #if bounds != self.bounds:
            #self.bounds = bounds
            #self.prepareGeometryChange()
        p.setRenderHints(p.Antialiasing, True)
        p.setPen(self.currentPen)
        
        #p.rotate(va * 180. / 3.1415926)
        #p.drawPath(self.path)        
        p.drawPath(self.shape())
        #ang = self.startAng + va
        #dt = 2*np.pi / self.sides
        #for i in range(0, self.sides):
            #x1 = size * cos(ang)
            #y1 = size * sin(ang)
            #x2 = size * cos(ang+dt)
            #y2 = size * sin(ang+dt)
            #ang += dt
            #p.drawLine(Point(x1, y1), Point(x2, y2))
            
    def shape(self):
        if self._shape is None:
            s = self.generateShape()
            if s is None:
Luke Campagnola's avatar
Luke Campagnola committed
1277
                return self.path
1278
            self._shape = s
Luke Campagnola's avatar
Luke Campagnola committed
1279
            self.prepareGeometryChange()  ## beware--this can cause the view to adjust, which would immediately invalidate the shape.
1280
1281
1282
        return self._shape
    
    def boundingRect(self):
1283
1284
1285
1286
1287
1288
        #print 'roi:', self.roi
        s1 = self.shape()
        #print "   s1:", s1
        #s2 = self.shape()
        #print "   s2:", s2
        
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
        return self.shape().boundingRect()
            
    def generateShape(self):
        ## determine rotation of transform
        #m = self.sceneTransform()  ## Qt bug: do not access sceneTransform() until we know this object has a scene.
        #mi = m.inverted()[0]
        
        dt = self.deviceTransform()
        
        if dt is None:
            self._shape = self.path
            return None
        
        v = dt.map(QtCore.QPointF(1, 0)) - dt.map(QtCore.QPointF(0, 0))
        va = np.arctan2(v.y(), v.x())
        
Luke Campagnola's avatar
Luke Campagnola committed
1305
        dti = fn.invertQTransform(dt)
1306
1307
1308
1309
1310
1311
1312
1313
        devPos = dt.map(QtCore.QPointF(0,0))
        tr = QtGui.QTransform()
        tr.translate(devPos.x(), devPos.y())
        tr.rotate(va * 180. / 3.1415926)
        
        return dti.map(tr.map(self.path))
        
        
1314
1315
    def viewRangeChanged(self):
        GraphicsObject.viewRangeChanged(self)
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
        self._shape = None  ## invalidate shape, recompute later if requested.
        #self.updateShape()
        
    #def itemChange(self, change, value):
        #if change == self.ItemScenePositionHasChanged:
            #self.updateShape()


class TestROI(ROI):
    def __init__(self, pos, size, **args):
        #QtGui.QGraphicsRectItem.__init__(self, pos[0], pos[1], size[0], size[1])
        ROI.__init__(self, pos, size, **args)
        #self.addTranslateHandle([0, 0])
        self.addTranslateHandle([0.5, 0.5])
        self.addScaleHandle([1, 1], [0, 0])
        self.addScaleHandle([0, 0], [1, 1])
        self.addScaleRotateHandle([1, 0.5], [0.5, 0.5])
        self.addScaleHandle([0.5, 1], [0.5, 0.5])
        self.addRotateHandle([1, 0], [0, 0])
        self.addRotateHandle([0, 1], [1, 1])



class RectROI(ROI):
    def __init__(self, pos, size, centered=False, sideScalers=False, **args):
        #QtGui.QGraphicsRectItem.__init__(self, 0, 0, size[0], size[1])
        ROI.__init__(self, pos, size, **args)
        if centered:
            center = [0.5, 0.5]
        else:
            center = [0, 0]
            
        #self.addTranslateHandle(center)
        self.addScaleHandle([1, 1], center)
        if sideScalers:
            self.addScaleHandle([1, 0.5], [center[0], 0.5])
            self.addScaleHandle([0.5, 1], [0.5, center[1]])

class LineROI(ROI):
    def __init__(self, pos1, pos2, width, **args):
        pos1 = Point(pos1)
        pos2 = Point(pos2)
        d = pos2-pos1
        l = d.length()
        ang = Point(1, 0).angle(d)
        ra = ang * np.pi / 180.
        c = Point(-width/2. * sin(ra), -width/2. * cos(ra))
        pos1 = pos1 + c
        
        ROI.__init__(self, pos1, size=Point(l, width), angle=ang, **args)
        self.addScaleRotateHandle([0, 0.5], [1, 0.5])
        self.addScaleRotateHandle([1, 0.5], [0, 0.5])
        self.addScaleHandle([0.5, 1], [0.5, 0.5])
        
Luke Campagnola's avatar
Luke Campagnola committed
1370

1371
        
Luke Campagnola's avatar
Luke Campagnola committed
1372
1373
1374
class MultiRectROI(QtGui.QGraphicsObject):
    """
    Chain of rectangular ROIs connected by handles. 
1375
    
Luke Campagnola's avatar
Luke Campagnola committed
1376
1377
1378
1379
    This is generally used to mark a curved path through 
    an image similarly to PolyLineROI. It differs in that each segment
    of the chain is rectangular instead of linear and thus has width.
    """
1380
1381
1382
1383
1384
1385
1386
1387
    sigRegionChangeFinished = QtCore.Signal(object)
    sigRegionChangeStarted = QtCore.Signal(object)
    sigRegionChanged = QtCore.Signal(object)
    
    def __init__(self, points, width, pen=None, **args):
        QtGui.QGraphicsObject.__init__(self)
        self.pen = pen
        self.roiArgs = args
Luke Campagnola's avatar
Luke Campagnola committed
1388
        self.lines = []
1389
1390
        if len(points) < 2:
            raise Exception("Must start with at least 2 points")
Luke Campagnola's avatar
Luke Campagnola committed
1391
1392
1393
1394
1395
1396
1397
1398
        
        ## create first segment
        self.addSegment(points[1], connectTo=points[0], scaleHandle=True)
        
        ## create remaining segments
        for p in points[2:]:
            self.addSegment(p)
        
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
        
    def paint(self, *args):
        pass
    
    def boundingRect(self):
        return QtCore.QRectF()
        
    def roiChangedEvent(self):
        w = self.lines[0].state['size'][1]
        for l in self.lines[1:]:
            w0 = l.state['size'][1]
1410
1411
            if w == w0:
                continue
1412
1413
1414
1415
1416
1417
1418
1419
1420
            l.scale([1.0, w/w0], center=[0.5,0.5])
        self.sigRegionChanged.emit(self)
            
    def roiChangeStartedEvent(self):
        self.sigRegionChangeStarted.emit(self)
        
    def roiChangeFinishedEvent(self):
        self.sigRegionChangeFinished.emit(self)
        
Luke Campagnola's avatar
Luke Campagnola committed
1421
1422
1423
1424
1425
1426
1427
    def getHandlePositions(self):
        """Return the positions of all handles in local coordinates."""
        pos = [self.mapFromScene(self.lines[0].getHandles()[0].scenePos())]
        for l in self.lines:
            pos.append(self.mapFromScene(l.getHandles()[1].scenePos()))
        return pos
        
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
    def getArrayRegion(self, arr, img=None, axes=(0,1)):
        rgns = []
        for l in self.lines:
            rgn = l.getArrayRegion(arr, img, axes=axes)
            if rgn is None:
                continue
                #return None
            rgns.append(rgn)
            #print l.state['size']
            
        ## make sure orthogonal axis is the same size
        ## (sometimes fp errors cause differences)
        ms = min([r.shape[axes[1]] for r in rgns])
        sl = [slice(None)] * rgns[0].ndim
        sl[axes[1]] = slice(0,ms)
        rgns = [r[sl] for r in rgns]
        #print [r.shape for r in rgns], axes
        
        return np.concatenate(rgns, axis=axes[0])
        
Luke Campagnola's avatar
Luke Campagnola committed
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
    def addSegment(self, pos=(0,0), scaleHandle=False, connectTo=None):
        """
        Add a new segment to the ROI connecting from the previous endpoint to *pos*.
        (pos is specified in the parent coordinate system of the MultiRectROI)
        """
        
        ## by default, connect to the previous endpoint
        if connectTo is None:
            connectTo = self.lines[-1].getHandles()[1]
            
        ## create new ROI
        newRoi = ROI((0,0), [1, 5], parent=self, pen=self.pen, **self.roiArgs)
        self.lines.append(newRoi)
        
        ## Add first SR handle
        if isinstance(connectTo, Handle):
            self.lines[-1].addScaleRotateHandle([0, 0.5], [1, 0.5], item=connectTo)
            newRoi.movePoint(connectTo, connectTo.scenePos(), coords='scene')
        else:
            h = self.lines[-1].addScaleRotateHandle([0, 0.5], [1, 0.5])
            newRoi.movePoint(h, connectTo, coords='scene')
            
        ## add second SR handle
        h = self.lines[-1].addScaleRotateHandle([1, 0.5], [0, 0.5]) 
        newRoi.movePoint(h, pos)
        
        ## optionally add scale handle (this MUST come after the two SR handles)
        if scaleHandle:
            newRoi.addScaleHandle([0.5, 1], [0.5, 0.5])
            
        newRoi.translatable = False 
        newRoi.sigRegionChanged.connect(self.roiChangedEvent) 
        newRoi.sigRegionChangeStarted.connect(self.roiChangeStartedEvent) 
        newRoi.sigRegionChangeFinished.connect(self.roiChangeFinishedEvent)
        self.sigRegionChanged.emit(self) 
    

    def removeSegment(self, index=-1): 
        """Remove a segment from the ROI."""
        roi = self.lines[index]
        self.lines.pop(index)
        self.scene().removeItem(roi)
        roi.sigRegionChanged.disconnect(self.roiChangedEvent) 
        roi.sigRegionChangeStarted.disconnect(self.roiChangeStartedEvent) 
        roi.sigRegionChangeFinished.disconnect(self.roiChangeFinishedEvent)
        
        self.sigRegionChanged.emit(self)
        
        
class MultiLineROI(MultiRectROI):
    def __init__(self, *args, **kwds):
        MultiRectROI.__init__(self, *args, **kwds)
        print("Warning: MultiLineROI has been renamed to MultiRectROI. (and MultiLineROI may be redefined in the future)")
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
        
class EllipseROI(ROI):
    def __init__(self, pos, size, **args):
        #QtGui.QGraphicsRectItem.__init__(self, 0, 0, size[0], size[1])
        ROI.__init__(self, pos, size, **args)
        self.addRotateHandle([1.0, 0.5], [0.5, 0.5])
        self.addScaleHandle([0.5*2.**-0.5 + 0.5, 0.5*2.**-0.5 + 0.5], [0.5, 0.5])
            
    def paint(self, p, opt, widget):
        r = self.boundingRect()
        p.setRenderHint(QtGui.QPainter.Antialiasing)
        p.setPen(self.currentPen)
        
        p.scale(r.width(), r.height())## workaround for GL bug
        r = QtCore.QRectF(r.x()/r.width(), r.y()/r.height(), 1,1)
        
        p.drawEllipse(r)
        
    def getArrayRegion(self, arr, img=None):
        arr = ROI.getArrayRegion(self, arr, img)
        if arr is None or arr.shape[0] == 0 or arr.shape[1] == 0:
            return None
        w = arr.shape[0]
        h = arr.shape[1]
        ## generate an ellipsoidal mask
        mask = np.fromfunction(lambda x,y: (((x+0.5)/(w/2.)-1)**2+ ((y+0.5)/(h/2.)-1)**2)**0.5 < 1, (w, h))
    
        return arr * mask
    
    def shape(self):
        self.path = QtGui.QPainterPath()
        self.path.addEllipse(self.boundingRect())
        return self.path
        
        
class CircleROI(EllipseROI):
    def __init__(self, pos, size, **args):
        ROI.__init__(self, pos, size, **args)
        self.aspectLocked = True
        #self.addTranslateHandle([0.5, 0.5])
        self.addScaleHandle([0.5*2.**-0.5 + 0.5, 0.5*2.**-0.5 + 0.5], [0.5, 0.5])
        
class PolygonROI(ROI):
Luke Campagnola's avatar
Luke Campagnola committed
1544
1545
    ## deprecated. Use PloyLineROI instead.
    
1546
1547
1548
1549
1550
1551
1552
1553
    def __init__(self, positions, pos=None, **args):
        if pos is None:
            pos = [0,0]
        ROI.__init__(self, pos, [1,1], **args)
        #ROI.__init__(self, positions[0])
        for p in positions:
            self.addFreeHandle(p)
        self.setZValue(1000)
Luke Campagnola's avatar
Luke Campagnola committed
1554
        print("Warning: PolygonROI is deprecated. Use PolyLineROI instead.")
1555
        
1556
1557
1558
1559
            
    def listPoints(self):
        return [p['item'].pos() for p in self.handles]
            
Luke Campagnola's avatar
Luke Campagnola committed
1560
1561
1562
1563
1564
    #def movePoint(self, *args, **kargs):
        #ROI.movePoint(self, *args, **kargs)
        #self.prepareGeometryChange()
        #for h in self.handles:
            #h['pos'] = h['item'].pos()
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
            
    def paint(self, p, *args):
        p.setRenderHint(QtGui.QPainter.Antialiasing)
        p.setPen(self.currentPen)
        for i in range(len(self.handles)):
            h1 = self.handles[i]['item'].pos()
            h2 = self.handles[i-1]['item'].pos()
            p.drawLine(h1, h2)
        
    def boundingRect(self):
        r = QtCore.QRectF()
        for h in self.handles:
            r |= self.mapFromItem(h['item'], h['item'].boundingRect()).boundingRect()   ## |= gives the union of the two QRectFs
        return r
    
    def shape(self):
        p = QtGui.QPainterPath()
        p.moveTo(self.handles[0]['item'].pos())
        for i in range(len(self.handles)):
            p.lineTo(self.handles[i]['item'].pos())
        return p
    
    def stateCopy(self):
        sc = {}
        sc['pos'] = Point(self.state['pos'])
        sc['size'] = Point(self.state['size'])
        sc['angle'] = self.state['angle']
        #sc['handles'] = self.handles
        return sc

1595
1596
1597
class PolyLineROI(ROI):
    """Container class for multiple connected LineSegmentROIs. Responsible for adding new 
    line segments, and for translation/(rotation?) of multiple lines together."""
1598
1599
    def __init__(self, positions, closed=False, pos=None, **args):
        
1600
1601
        if pos is None:
            pos = [0,0]
1602
1603
1604
        #pen=args.get('pen', fn.mkPen((100,100,255)))
        ROI.__init__(self, pos, size=[1,1], **args)
        self.closed = closed
1605
1606
        self.segments = []
        
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
        for p in positions:
            self.addFreeHandle(p)
         
        start = -1 if self.closed else 0
        for i in range(start, len(self.handles)-1):
            self.addSegment(self.handles[i]['item'], self.handles[i+1]['item'])
        #for i in range(len(positions)-1):
            #h2 = self.addFreeHandle(positions[i+1])
            #segment = LineSegmentROI(handles=(h, h2), pen=pen, parent=self, movable=False)
            #self.segments.append(segment)
            #h = h2
1618
1619
            
        
1620
1621
1622
1623
        #for i, s in enumerate(self.segments):
            #h = s.handles[0]
            #self.addFreeHandle(h['pos'], item=h['item'])
            #s.setZValue(self.zValue() +1)
1624
           
1625
1626
        #h = self.segments[-1].handles[1]
        #self.addFreeHandle(h['pos'], item=h['item'])
1627
            
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
        #if closed:
            #h1 = self.handles[-1]['item']
            #h2 = self.handles[0]['item']
            #self.segments.append(LineSegmentROI([positions[-1], positions[0]], pos=pos, handles=(h1, h2), pen=pen, parent=self, movable=False))
            #h2.setParentItem(self.segments[-1])
            
            
        #for s in self.segments:
            #self.setSegmentSettings(s)
            
    #def movePoint(self, *args, **kargs):
1639
        #pass
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650

    def addSegment(self, h1, h2, index=None):
        seg = LineSegmentROI(handles=(h1, h2), pen=self.pen, parent=self, movable=False)
        if index is None:
            self.segments.append(seg)
        else:
            self.segments.insert(index, seg)
        seg.sigClicked.connect(self.segmentClicked)
        seg.setAcceptedMouseButtons(QtCore.Qt.LeftButton)
        seg.setZValue(self.zValue()+1)
        for h in seg.handles:
1651
1652
1653
1654
1655
            h['item'].setDeletable(True)
            h['item'].setAcceptedMouseButtons(h['item'].acceptedMouseButtons() | QtCore.Qt.LeftButton) ## have these handles take left clicks too, so that handles cannot be added on top of other handles
        
    def setMouseHover(self, hover):
        ## Inform all the ROI's segments that the mouse is(not) hovering over it
1656
1657
1658
1659
        #if self.mouseHovering == hover:
            #return
        #self.mouseHovering = hover
        ROI.setMouseHover(self, hover)
1660
1661
        for s in self.segments:
            s.setMouseHover(hover)
1662
1663
1664
1665
1666
1667
1668
          
    def addHandle(self, info, index=None):
        h = ROI.addHandle(self, info, index=index)
        h.sigRemoveRequested.connect(self.removeHandle)
        return h
        
    def segmentClicked(self, segment, ev=None, pos=None): ## pos should be in this item's coordinate system
1669
1670
1671
1672
1673
1674
        if ev != None:
            pos = segment.mapToParent(ev.pos())
        elif pos != None:
            pos = pos
        else:
            raise Exception("Either an event or a position must be given.")
1675
1676
        h1 = segment.handles[0]['item']
        h2 = segment.handles[1]['item']
1677
        
1678
1679
1680
1681
        i = self.segments.index(segment)
        h3 = self.addFreeHandle(pos, index=self.indexOfHandle(h2))
        self.addSegment(h3, h2, index=i+1)
        segment.replaceHandle(h2, h3)
1682
        
1683
1684
1685
1686
1687
1688
1689
1690

    #def report(self):
        #for s in self.segments:
            #print s
            #for h in s.handles:
                #print "  ", h
        #for h in self.handles:
            #print h
1691
        
1692
1693
1694
1695
1696
1697
1698
    def removeHandle(self, handle, updateSegments=True):
        ROI.removeHandle(self, handle)
        handle.sigRemoveRequested.disconnect(self.removeHandle)
        
        if not updateSegments:
            return
        segments = handle.rois[:]
1699
        
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
        if len(segments) == 1:
            self.removeSegment(segments[0])
        else:
            handles = [h['item'] for h in segments[1].handles]
            handles.remove(handle)
            segments[0].replaceHandle(handle, handles[0])
            self.removeSegment(segments[1])
        
    def removeSegment(self, seg):
        for handle in seg.handles[:]:
            seg.removeHandle(handle['item'])
        self.segments.remove(seg)
        seg.sigClicked.disconnect(self.segmentClicked)
        self.scene().removeItem(seg)
        
    def checkRemoveHandle(self, h):
        ## called when a handle is about to display its context menu
        if self.closed:
            return len(self.handles) > 3