Ejemplo n.º 1
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Assignment")
        self.scene = QGraphicsScene()
        self.button = QPushButton("Draw Text Boxes")
        #        self.image = QImage(self.size(), QImage.Format_RGB32)
        #        self.image.fill(Qt.black)
        self.scene.addWidget(self.button)

        self.view = QGraphicsView(self.scene)
        #        self.view.resize(800, 600)
        self.setCentralWidget(self.view)

        self.button.clicked.connect(self.buttonClicked)
        self.view.viewport().installEventFilter(self)

        self.drawing = False
        self.brushSize = 2
        self.brushColor = Qt.black
        self.lastPoint = QPoint()

    def mousePressEvent(self, event):
        #        super(MainWindow, self).mousePressEvent(event)
        if event.button() == Qt.LeftButton:
            self.drawing = True
            self.startPoint = event.pos()
            print(self.drawing)

    def mouseReleaseEvent(self, event):
        if (Qt.LeftButton & self.drawing):
            self.lastPoint = event.pos()
            print(self.startPoint)
            painter = QPainter()
            painter.setPen(
                QPen(self.brushColor, self.brushSize, Qt.SolidLine,
                     Qt.RoundCap, Qt.RoundJoin))
            painter.drawRect(QtCore.QRect(self.startPoint, self.lastPoint))
            self.update()


#    def paintEvent(self, event):
#        canvasPainter = QPainter(self)
#        canvasPainter.drawImage(self.rect())

    def buttonClicked(self):
        self.button.hide()

    def eventFilter(self, obj, event):
        if obj is self.view.viewport():
            if event.type() == QEvent.MouseButtonPress:
                print('mouse press event = ', event.pos())
            elif event.type() == QEvent.MouseButtonRelease:
                self.mouseReleaseEvent(event)
                print('mouse release event = ', event.pos())

        return QWidget.eventFilter(self, obj, event)
Ejemplo n.º 2
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Assignment")
        self.scene = QGraphicsScene()
        self.resize(800, 600)
        self.button = QPushButton("Draw Text Boxes")

        self.scene.addWidget(self.button)

        self.view = QGraphicsView()
        self.view.setScene(self.scene)
        self.setCentralWidget(self.view)
        self.button.clicked.connect(self.buttonClicked)
        self.view.viewport().installEventFilter(self)

        self.drawing = False
        self.lastPoint = QPoint()
        self.startPoint = QPoint()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.startPoint = self.view.mapToScene(event.pos())
            self.drawing = True

    def mouseReleaseEvent(self, event):
        if Qt.LeftButton and self.drawing:
            self.lastPoint = self.view.mapToScene(event.pos())
            self.update()

    def paintEvent(self, event):

        if self.drawing :

            self.view.le = QPlainTextEdit()
            width = QtCore.QRectF(self.startPoint, self.lastPoint).size().width()
            height = QtCore.QRectF(self.startPoint, self.lastPoint).size().height()
            x = self.startPoint.x()
            y = self.startPoint.y()
            if width > 1 and height > 1:
                self.view.le.setGeometry(x, y, width, height)
                self.qsizegrip = QSizeGrip(self.view.le)
                self.scene.addWidget(self.view.le)

    def buttonClicked(self):
        self.button.hide()

    def eventFilter(self, obj, event):
        if obj is self.view.viewport():
            if event.type() == QEvent.MouseButtonPress:
                pass
#                self.mousePressEvent(event)
            elif event.type() == QEvent.MouseButtonRelease:
                self.mouseReleaseEvent(event)
        return QWidget.eventFilter(self, obj, event)
Ejemplo n.º 3
0
class AddItem(UsesQApplication):
    '''Tests for QGraphicsScene.add*'''

    qapplication = True

    def setUp(self):
        #Acquire resources
        super(AddItem, self).setUp()
        self.scene = QGraphicsScene()
        # While the scene does not inherits from QWidget, requires
        # an application to make the internals work.

    def tearDown(self):
        #Release resources
        del self.scene
        super(AddItem, self).tearDown()

    def testEllipse(self):
        #QGraphicsScene.addEllipse
        item = self.scene.addEllipse(100, 100, 100, 100)
        self.assertTrue(isinstance(item, QGraphicsEllipseItem))

    def testLine(self):
        #QGraphicsScene.addLine
        item = self.scene.addLine(100, 100, 200, 200)
        self.assertTrue(isinstance(item, QGraphicsLineItem))

    def testPath(self):
        #QGraphicsScene.addPath
        item = self.scene.addPath(QPainterPath())
        self.assertTrue(isinstance(item, QGraphicsPathItem))

    def testPixmap(self):
        #QGraphicsScene.addPixmap
        item = self.scene.addPixmap(QPixmap())
        self.assertTrue(isinstance(item, QGraphicsPixmapItem))

    def testPolygon(self):
        #QGraphicsScene.addPolygon
        points = [QPointF(0, 0), QPointF(100, 100), QPointF(0, 100)]
        item = self.scene.addPolygon(QPolygonF(points))
        self.assertTrue(isinstance(item, QGraphicsPolygonItem))

    def testRect(self):
        #QGraphicsScene.addRect
        item = self.scene.addRect(100, 100, 100, 100)
        self.assertTrue(isinstance(item, QGraphicsRectItem))

    def testSimpleText(self):
        #QGraphicsScene.addSimpleText
        item = self.scene.addSimpleText('Monty Python 42')
        self.assertTrue(isinstance(item, QGraphicsSimpleTextItem))

    def testText(self):
        #QGraphicsScene.addText
        item = self.scene.addText('Monty Python 42')
        self.assertTrue(isinstance(item, QGraphicsTextItem))

    def testWidget(self):
        #QGraphicsScene.addWidget
        # XXX: printing some X11 error when using under PyQt4
        item = self.scene.addWidget(QPushButton())
        self.assertTrue(isinstance(item, QGraphicsProxyWidget))
Ejemplo n.º 4
0
class AddItem(UsesQApplication):
    '''Tests for QGraphicsScene.add*'''

    qapplication = True

    def setUp(self):
        #Acquire resources
        super(AddItem, self).setUp()
        self.scene = QGraphicsScene()
        # While the scene does not inherits from QWidget, requires
        # an application to make the internals work.

    def tearDown(self):
        #Release resources
        del self.scene
        super(AddItem, self).tearDown()

    def testEllipse(self):
        #QGraphicsScene.addEllipse
        item = self.scene.addEllipse(100, 100, 100, 100)
        self.assertTrue(isinstance(item, QGraphicsEllipseItem))

    def testLine(self):
        #QGraphicsScene.addLine
        item = self.scene.addLine(100, 100, 200, 200)
        self.assertTrue(isinstance(item, QGraphicsLineItem))

    def testPath(self):
        #QGraphicsScene.addPath
        item = self.scene.addPath(QPainterPath())
        self.assertTrue(isinstance(item, QGraphicsPathItem))

    def testPixmap(self):
        #QGraphicsScene.addPixmap
        item = self.scene.addPixmap(QPixmap())
        self.assertTrue(isinstance(item, QGraphicsPixmapItem))

    def testPolygon(self):
        #QGraphicsScene.addPolygon
        points = [QPointF(0, 0), QPointF(100, 100), QPointF(0, 100)]
        item = self.scene.addPolygon(QPolygonF(points))
        self.assertTrue(isinstance(item, QGraphicsPolygonItem))

    def testRect(self):
        #QGraphicsScene.addRect
        item = self.scene.addRect(100, 100, 100, 100)
        self.assertTrue(isinstance(item, QGraphicsRectItem))

    def testSimpleText(self):
        #QGraphicsScene.addSimpleText
        item = self.scene.addSimpleText('Monty Python 42')
        self.assertTrue(isinstance(item, QGraphicsSimpleTextItem))

    def testText(self):
        #QGraphicsScene.addText
        item = self.scene.addText('Monty Python 42')
        self.assertTrue(isinstance(item, QGraphicsTextItem))

    def testWidget(self):
        #QGraphicsScene.addWidget
        # XXX: printing some X11 error when using under PyQt4
        item = self.scene.addWidget(QPushButton())
        self.assertTrue(isinstance(item, QGraphicsProxyWidget))
Ejemplo n.º 5
0
class graphicsForm3DLUT(baseGraphicsForm):
    """
    Form for 3D LUT editing.

    """
    # node markers
    qpp0 = activeNode.qppR
    qpp1 = activeNode.qppE
    selectBrush = QBrush(QColor(255, 255, 255))
    unselectBrush = QBrush()
    # default brightness
    defaultColorWheelBr = 0.60

    @classmethod
    def getNewWindow(cls, cModel, targetImage=None, axeSize=500, LUTSize=LUTSIZE, layer=None, parent=None, mainForm=None):
        """
        build a graphicsForm3DLUT object. The parameter size represents the size of
        the color wheel, border not included (the size of the window is adjusted).
        @param cModel
        @type cModel:
        @param targetImage
        @type targetImage:
        @param axeSize: size of the color wheel (default 500)
        @type axeSize:
        @param LUTSize: size of the LUT
        @type LUTSize:
        @param layer: layer of targetImage linked to graphics form
        @type layer:
        @param parent: parent widget
        @type parent:
        @param mainForm:
        @type mainForm:
        @return: graphicsForm3DLUT object
        @rtype:
        """
        try:
            QApplication.setOverrideCursor(Qt.WaitCursor)
            QApplication.processEvents()
            newWindow = graphicsForm3DLUT(cModel, targetImage=targetImage, axeSize=axeSize, LUTSize=LUTSize,
                                          layer=layer, parent=parent, mainForm=mainForm)
            newWindow.setWindowTitle(layer.name)
        finally:
            QApplication.restoreOverrideCursor()
            QApplication.processEvents()
        return newWindow

    def __init__(self, cModel, targetImage=None, axeSize=500, LUTSize=LUTSIZE, layer=None, parent=None, mainForm=None):
        """
        @param cModel: color space used by colorPicker, slider2D and colorPicker
        @type cModel: cmConverter object
        @param axeSize: size of the color wheel
        @type axeSize: int
        @param targetImage:
        @type targetImage: imImage
        @param LUTSize:
        @type LUTSize: int
        @param layer: layer of targetImage linked to graphics form
        @type layer : QLayer
        @param parent:
        @type parent:
        """
        super().__init__(parent=parent)
        self.mainForm = mainForm  # used by saveLUT()
        # context help tag
        self.helpId = "LUT3DForm"
        self.cModel = cModel
        border = 20
        self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        self.setMinimumSize(axeSize + 90, axeSize + 200)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setBackgroundBrush(QBrush(Qt.black, Qt.SolidPattern))
        self.currentHue, self.currentSat, self.currentPb = 0, 0, self.defaultColorWheelBr
        self.currentR, self.currentG, self.currentB = 0, 0, 0
        self.size = axeSize
        # back links to image
        self.targetImage = weakProxy(targetImage)
        self.layer = weakProxy(layer)
        # currently selected grid node
        self.selected = None
        self.graphicsScene = QGraphicsScene()
        self.graphicsScene.options = None
        self.setScene(self.graphicsScene)
        # back to image layer
        self.graphicsScene.layer = weakProxy(layer)
        # init LUT
        freshLUT3D = LUT3D(None, size=LUTSize, alpha=True)
        self.graphicsScene.lut = freshLUT3D
        # init 2D slider
        QImg = hueSatPattern(axeSize, axeSize, cModel, bright=self.defaultColorWheelBr, border=border)
        self.graphicsScene.slider2D = colorChooser(cModel, QImg, target=self.targetImage, size=axeSize, border=border)
        self.graphicsScene.selectMarker = activeMarker.fromCross(parent=self.graphicsScene.slider2D)
        self.graphicsScene.selectMarker.setPos(axeSize / 2, axeSize / 2)
        # color wheel event handler
        def f1(p, r, g, b):
            h, s, br = self.cModel.rgb2cm(r, g, b)
            self.currentHue, self.currentSat, self.currentPb = h, s, br
            self.currentR, self.currentG, self.currentB = r, g, b
            self.bSliderUpdate()
            self.displayStatus()
        self.graphicsScene.slider2D.onMouseRelease = f1
        self.graphicsScene.addItem(self.graphicsScene.slider2D)

        # Brightness slider
        self.bSliderHeight = 20
        self.bSliderWidth = self.graphicsScene.slider2D.QImg.width()
        px = brightnessPattern(self.bSliderWidth, self.bSliderHeight, cModel, self.currentHue, self.currentSat).rPixmap
        self.graphicsScene.bSlider = QGraphicsPixmapItem(px, parent=self.graphicsScene.slider2D)
        self.graphicsScene.bSlider.setPos(QPointF(-border, self.graphicsScene.slider2D.QImg.height() - border))
        bSliderCursor = activeMarker.fromTriangle(parent=self.graphicsScene.bSlider)
        bSliderCursor.setMoveRange(QRectF(0.0, bSliderCursor.size, self.graphicsScene.bSlider.pixmap().width(), 0.0))
        bSliderCursor.setPos(self.graphicsScene.bSlider.pixmap().width() * self.defaultColorWheelBr, bSliderCursor.size)
        # cursor event handlers

        def f2(e, p, q):
            self.currentPb = p / float(self.bSliderWidth)
            QToolTip.showText(e.screenPos(), (str(int(self.currentPb * 100.0))), self)
        bSliderCursor.onMouseMove = f2

        def f3(e, p, q):
            self.currentPb = p / float(self.bSliderWidth)
            self.graphicsScene.slider2D.QImg.setPb(self.currentPb)
            self.graphicsScene.slider2D.setPixmap(self.graphicsScene.slider2D.QImg.rPixmap)
            self.displayStatus()
        bSliderCursor.onMouseRelease = f3
        # status bar
        offset = 60
        self.graphicsScene.statusBar = QGraphicsTextItem()
        self.graphicsScene.statusBar.setPos(-20, axeSize + offset)
        self.graphicsScene.statusBar.setDefaultTextColor(QColor(255, 255, 255))
        self.graphicsScene.statusBar.setPlainText('')
        self.graphicsScene.addItem(self.graphicsScene.statusBar)

        self.displayStatus()

        # self.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)

        # grid
        self.grid = activeGrid(self.graphicsScene.lut.size, self.cModel, parent=self.graphicsScene.slider2D)
        self.graphicsScene.grid = self.grid

        # buttons
        pushButton1 = QbLUePushButton("Reset Grid")
        pushButton1.clicked.connect(self.onReset)
        pushButton2 = QbLUePushButton("Save LUT")
        pushButton2.clicked.connect(self.saveLUT)
        pushButton3 = QbLUePushButton("Smooth Grid")
        pushButton3.clicked.connect(self.onSmoothGrid)
        pushButton4 = QbLUePushButton('Set Mask')
        pushButton4.clicked.connect(self.setMask)
        # pushButton4 needs enabling/disabling
        self.pushButton4 = pushButton4

        # options
        options1, optionNames1 = ['use image', 'use selection'], ['Use Image', 'Use Selection']
        self.listWidget1 = optionsWidget(options=options1, optionNames=optionNames1, exclusive=True)
        """
        def onSelect1(item):
            self.graphicsScene.options['use selection'] = item is self.listWidget1.items['use selection']
        self.listWidget1.onSelect = onSelect1
        """
        self.listWidget1.setFocusPolicy(Qt.NoFocus)
        # set initial selection to 'use image'
        self.listWidget1.checkOption(self.listWidget1.intNames[0])

        options2, optionNames2 = ['add node', 'remove node'], ['Add Node', 'Remove Node']
        self.listWidget2 = optionsWidget(options=options2, optionNames=optionNames2, exclusive=True)
        """
        def onSelect2(item):
            self.graphicsScene.options['add node'] = item is self.listWidget2.items['add node']
        self.listWidget2.onSelect = onSelect2
        """
        # set initial selection to add node'
        self.listWidget2.checkOption(self.listWidget2.intNames[0])

        options3 = ['select neighbors', 'reset removed nodes', 'show histogram', 'keep alpha']
        optionNames3 = ['Select Neighbors', 'Reset Removed', 'Show Histogram', 'Keep Alpha']
        self.listWidget3 = optionsWidget(options=options3, optionNames=optionNames3, exclusive=False)
        self.listWidget3.checkOption(self.listWidget3.intNames[0])
        self.listWidget3.checkOption(self.listWidget3.intNames[1])

        def onSelect3(item):
            option = item.internalName
            if option == 'show histogram':
                self.graphicsScene.slider2D.showTargetHist = self.graphicsScene.options[option]  # .isChecked()
                self.graphicsScene.slider2D.updatePixmap()
                return
            if option == 'keep alpha':
                self.enableButtons()
                self.layer.applyToStack()

        self.listWidget3.onSelect = onSelect3
        # set initial selection to 'select naighbors'
        item = self.listWidget3.items[options3[0]]
        item.setCheckState(Qt.Checked)
        self.graphicsScene.options = UDict((self.listWidget1.options, self.listWidget2.options,
                                            self.listWidget3.options))
        # layouts
        hlButtons = QHBoxLayout()
        hlButtons.addWidget(pushButton1)
        hlButtons.addWidget(pushButton3)
        hlButtons.addWidget(pushButton2)
        hl = QHBoxLayout()
        vl1 = QVBoxLayout()
        vl1.addWidget(self.listWidget1)
        vl1.addWidget(pushButton4)
        hl.addLayout(vl1)
        hl.addWidget(self.listWidget2)
        hl.addWidget(self.listWidget3)
        vl = QVBoxLayout()
        for l in [hlButtons, hl]:
            vl.addLayout(l)
        # Init QWidget container for adding buttons and options to graphicsScene
        container = QWidget()
        container.setObjectName("container")
        container.setLayout(vl)
        ss = """QWidget#container{background: black}\
                QListWidget{background-color: black; selection-background-color: black; border: none; font-size: 7pt}\
                QListWidget::item{color: white;}\
                QListWidget::item::selected{background: black; border: none}"""
        container.setStyleSheet(ss)
        for wdg in [self.listWidget1, self.listWidget2, self.listWidget3]:
            wdg.setMinimumWidth(wdg.sizeHintForColumn(0))
            wdg.setMinimumHeight(wdg.sizeHintForRow(0)*len(wdg.items))
        container.setGeometry(-offset//2, axeSize + offset - 20, axeSize + offset, 20)
        self.graphicsScene.addWidget(container)

        #container.setStyleSheet("QPushButton {color: white;}\
         #                       QPushButton:pressed, QPushButton:hover {background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #0d5ca6, stop: 1 #2198c0);}")
        self.setWhatsThis(
""" <b>2.5D LUT Editor</b><br>
  HSpB layers are slower than HSV, but usually they give better results.<br>
  <b>Select nodes</b> with mouse clicks on the image. Selected nodes are shown
as small black circles on the color wheel.<br>
<b>Modify the color</b> of a node by dragging it on
the wheel. Several nodes can be moved simultaneously by grouping them.<br>
<b>Group nodes</b> :<br>
        &nbsp; 1 - select them with the mouse : while pressing the mouse left button, drag a rubber band around the nodes to select;<br>
        &nbsp; 2 - next, right click any one of the selected nodes and choose group from the context menu<br>
<b>unselect nodes</b> :<br>
        &nbsp; 1 - check the option Remove Node;<br>
        &nbsp; 2 -  ungroup;<br>
        &nbsp; 3 - on the image, click the pixels to unselect.<br>
<b>Caution</b> : Selecting nodes with the mouse is enabled only when
the Color Chooser is closed.<br>
Click the <b> Smooth Grid</b> button to smooth color transitions between neighbor nodes.<br>
Check the <br>Keep Alpha</b> option to forward the alpha channel without modifications.<br>
This option must be unchecked to build a mask from the 3D LUT.<br>
"""
                          )  # end of setWhatsThis

    def selectGridNode(self, r, g, b):
        """
        select the nearest grid nodes corresponding to r,g,b values.
        @param r: color
        @param g: color
        @param b: color
        """
        # surrounding cube
        # LUTNeighborhood = [(i,j,k) for i in [r/w, (r/w)+1] for j in [g/w, (g/w)+1] for k in [b/w, (b/w)+1]]

        # reset previous selected marker
        if self.selected is not None:
            self.selected.setPath(self.qpp1)
            self.selected.setBrush(self.unselectBrush)

        h, s, p = self.cModel.rgb2cm(r, g, b)  # , perceptual=True)
        # hspNeighborhood=[rgb2ccm(i * w, j * w, k * w, perceptual=True) for (i, j, k) in LUTNeighborhood if (i * w <= 255 and j * w <= 255 and k * w <= 255)]
        # currently selected values in adjust layer
        self.currentHue, self.currentSat, self.currentPb = h, s, p
        self.currentR, self.currentG, self.currentB = r, g, b
        # x, y : color wheel (cartesian origin top left corner) coordinates of the pixel corresponding to hue=h and sat=s
        xc, yc = self.graphicsScene.slider2D.QImg.GetPoint(h, s)

        # xyNeighborhood=[self.graphicsScene.slider2D.QImg.GetPoint(h, s) for h,s,_ in hspNeighborhood]

        # unitary coordinate increment between consecutive nodes
        step = float(self.grid.step)
        border = self.graphicsScene.slider2D.border
        # grid coordinates
        xcGrid, ycGrid = xc - border, yc - border
        # NNN = self.grid.gridNodes[int(round(ycGrid/step))][int(round(xcGrid/step))]
        NNN = self.grid.gridNodes[int(np.floor(ycGrid / step))][int(np.floor(xcGrid / step))]

        # select and mark selected node
        mode = self.graphicsScene.options['add node']
        if self.selected is not None:
            self.selected.setSelected(False)
        self.selected = NNN
        self.selected.setSelected(True)
        self.selected.setBrush(self.selectBrush)
        self.selected.setPath(self.qpp0)
        self.selected.setVisible(mode)
        nodesToSelect = NNN.neighbors() if self.graphicsScene.options['select neighbors'] else [NNN]
        for n in nodesToSelect:
            n.setVisible(mode)
            if self.graphicsScene.options['reset removed nodes'] and not mode:
                if isinstance(n.parentItem(), nodeGroup):
                    n.parentItem().removeFromGroup(n)
                n.setPos(n.initialPos)
                n.setState(n.initialPos)
            """
            for item in n.LUTIndices:
                #self.scene().lut.LUT3DArray[item.ind + (3,)] = 255  # TODO added 24/11/18
                i, j, k = item.ind
                self.scene().lut.LUT3DArray[k, j, i, 3] = 255  # TODO added 24/11/18
            """
        # update status
        self.onSelectGridNode(h, s)

    def displayStatus(self):
        s1 = ('h : %d  ' % self.currentHue) + ('s : %d  ' % (self.currentSat * 100))  # + ('p : %d  ' % (self.currentPb * 100))
        self.graphicsScene.statusBar.setPlainText(s1)  # + '\n' + s3 + '\n' + s2)

    def bSliderUpdate(self):
        px = brightnessPattern(self.bSliderWidth, self.bSliderHeight, self.cModel, self.currentHue, self.currentSat).rPixmap
        self.graphicsScene.bSlider.setPixmap(px)

    def onSelectGridNode(self, h, s):
        self.bSliderUpdate()
        self.displayStatus()

    def onSmoothGrid(self):
        """
        Button slot
        """
        self.grid.smooth()
        self.grid.drawGrid()
        self.layer.applyToStack()
        self.layer.parentImage.onImageChanged()
        # if getattr(self.layer.parentImage, 'window', None) is not None:
        # self.layer.parentImage.window.repaint()  # TODO modified 28/11/18 validate

    def onReset(self):
        """
        reset grid and LUT
        """
        # get a fresh LUT
        self.graphicsScene.lut = LUT3D(None, size=self.graphicsScene.lut.size, alpha=True)
        # explode all node groups
        groupList = [item for item in self.grid.childItems() if type(item) is nodeGroup]
        for item in groupList:
            item.prepareGeometryChange()
            self.scene().destroyItemGroup(item)
        # reset grid
        self.grid.reset()
        self.selected = None
        self.grid.drawGrid()
        self.layer.applyToStack()
        self.layer.parentImage.onImageChanged()
        # if getattr(self.layer.parentImage, 'window', None) is not None:
        # self.layer.parentImage.window.repaint()  # TODO modified 28/11/18 validate

    def enableButtons(self):
        self.pushButton4.setEnabled(not self.graphicsScene.options['keep alpha'])

    def saveLUT(self):
        """

        """
        mainForm = self.mainForm
        lut = self.scene().lut
        lastDir = str(mainForm.settings.value('paths/dlg3DLUTdir', '.'))
        dlg = QFileDialog(mainForm, "Save Color LUT", lastDir)
        dlg.setNameFilter('*.cube')
        dlg.setDefaultSuffix('cube')
        try:
            if dlg.exec_():
                filenames = dlg.selectedFiles()
                newDir = dlg.directory().absolutePath()
                mainForm.settings.setValue('paths/dlg3DLUTdir', newDir)
                lut.writeToTextFile(filenames[0])
                dlgInfo('3D LUT written')
        except IOError as e:
            dlgWarn(str(e))

    def setMask(self):
        """
        Build the layer mask from the image alpha channel.
        The Image alpha channel is recorded
        in the red channel of the mask.
        """
        layer = self.graphicsScene.layer
        currentImg = layer.getCurrentImage()
        imgBuf = QImageBuffer(currentImg)
        # resize the alpha channel
        imgmask = cv2.resize(imgBuf[:, :, 3], (layer.width(), layer.height()))
        mask = QImageBuffer(layer.mask)
        mask[:, :, 2] = imgmask
        layer.applyToStack()
        layer.parentImage.onImageChanged()


    def writeToStream(self, outStream):
        layer = self.layer
        outStream.writeQString(layer.actionName)
        outStream.writeQString(layer.name)
        outStream.writeInt32(self.graphicsScene.LUTSize)
        outStream.writeInt32(self.graphicsScene.lut.step)
        byteData = self.graphicsScene.lut.LUT3DArray.tostring()
        outStream.writeInt32(len(byteData))
        outStream.writeRawData(byteData)
        return outStream

    def readFromStream(self, inStream):
        actionName = inStream.readQString()
        name = inStream.readQString()
        size = inStream.readInt32()
        self.graphicsScene.LUTsize = size
        self.graphicsScene.lut.step = inStream.readInt32()
        l = inStream.readInt32()
        byteData = inStream.readRawData(l)
        self.graphicsScene.lut.LUT3DArray = np.fromstring(byteData, dtype=int).reshape((size, size, size, 3))
        return inStream
Ejemplo n.º 6
0
class TMSTester(QMainWindow):
    def __init__(self, width, height):
        super(TMSTester, self).__init__(None)

        self.setStyleSheet("background: transparent")

        self.canvasSize = QRectF(QPointF(0, 0), QPointF(width, height))

        self.view = QGraphicsView()
        self.view.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
        self.view.setDragMode(QGraphicsView.ScrollHandDrag)
        self.scene = QGraphicsScene(0, 0, width, height, self.view)
        self.view.setScene(self.scene)

        self.centreCoordinate = QPointF(-32.2138204, 115.0387413)
        self.zoom = 3
        self.mapLayer = TMSLayer('CRUSE:World_Bathymetric_Heightmap',
                                 self.canvasSize, self.centreCoordinate, 3)
        self.mapLayerHandle = self.scene.addWidget(self.mapLayer)
        self.setCentralWidget(self.view)
        self.mapLayer.setFocus()

    def mouseMoveEvent(self, event):

        tcX = self.mapLayer.requiredTiles['left']
        tcY = self.mapLayer.requiredTiles['top']
        offsetX = self.mapLayer.canvasSize.width() / 2 - (
            self.mapLayer.centrePoint.x() - tcX) * TILE_DIMENSION
        offsetY = self.mapLayer.canvasSize.height() / 2 + (
            self.mapLayer.centrePoint.y() - (tcY + 1)) * TILE_DIMENSION

        xTile = tcX + ((event.pos().x() - offsetX) / 256)
        yTile = (tcY + 1) - ((event.pos().y() - offsetY) / 256)
        self.mapLayer.centreCoordinate = self.mapLayer.tileToGeographic(
            xTile, yTile, self.mapLayer.tileZoomIndex)
        print('{}'.format(self.mapLayer.centreCoordinate))

    def mousePressEvent(self, event):

        tcX = self.mapLayer.requiredTiles['left']
        tcY = self.mapLayer.requiredTiles['top']
        offsetX = self.mapLayer.canvasSize.width() / 2 - (
            self.mapLayer.centrePoint.x() - tcX) * TILE_DIMENSION
        offsetY = self.mapLayer.canvasSize.height() / 2 + (
            self.mapLayer.centrePoint.y() - (tcY + 1)) * TILE_DIMENSION

        xTile = tcX + ((event.pos().x() - offsetX) / 256)
        yTile = (tcY + 1) - ((event.pos().y() - offsetY) / 256)
        centreCoordinate = self.mapLayer.tileToGeographic(
            xTile, yTile, self.mapLayer.tileZoomIndex)

        self.mapLayer.updateCentre(centreCoordinate)

    def wheelEvent(self, event):
        '''
        Only used for zooming.
        '''
        self.view.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
        self.view.viewport().installEventFilter(self)

        if event.delta() > 0:
            self.zoom *= 1 + (event.delta() / 120) * 0.1
            scale = 1 + (self.zoom % self.mapLayer.tileZoomIndex)
        else:
            self.zoom *= (1 + (event.delta() / 120) * 0.1)
            scale = 1 / (1 + (self.zoom % self.mapLayer.tileZoomIndex))

        rasterZoom = self.mapLayer.tileZoomIndex + 2**(
            floor(log(self.zoom, 2)) + 0) - 1

        if scale <= 2:
            self.view.scale(scale, scale)
        else:
            self.view.scale(1 / scale, 1 / scale)
            self.mapLayer.updateZoom(rasterZoom)

        print('zoom:{} scale:{} raster:{}'.format(self.zoom, scale,
                                                  rasterZoom))

    def eventFilter(self, qobject, event):
        if (event.type() == QEvent.Wheel):
            return True
        else:
            return False

    def keyPressEvent(self, event):

        if event.key() == Qt.Key_Left:
            self.centreCoordinate = QPointF(
                self.mapLayer.centreCoordinate.x(),
                self.mapLayer.centreCoordinate.y() -
                self.mapLayer.tileZoomIndex)
            self.mapLayer.updateCentre(self.centreCoordinate)
        if event.key() == Qt.Key_Right:
            self.centreCoordinate = QPointF(
                self.mapLayer.centreCoordinate.x(),
                self.mapLayer.centreCoordinate.y() +
                self.mapLayer.tileZoomIndex)
            self.mapLayer.updateCentre(self.centreCoordinate)
        if event.key() == Qt.Key_Up:
            self.centreCoordinate = QPointF(
                self.mapLayer.centreCoordinate.x() +
                self.mapLayer.tileZoomIndex,
                self.mapLayer.centreCoordinate.y())
            self.mapLayer.updateCentre(self.centreCoordinate)
        if event.key() == Qt.Key_Down:
            self.centreCoordinate = QPointF(
                self.mapLayer.centreCoordinate.x() -
                self.mapLayer.tileZoomIndex,
                self.mapLayer.centreCoordinate.y())
            self.mapLayer.updateCentre(self.centreCoordinate)
        if event.key() == Qt.Key_Z:
            self.zoom *= 1.3
            self.mapLayer.updateZoom(self.zoom)
        if event.key() == Qt.Key_X:
            self.zoom /= 1.3
            self.mapLayer.updateZoom(self.zoom)
        if event.key() == Qt.Key_P:
            self.centreCoordinate = QPointF(-32.2138204, 115.0387413)
            self.mapLayer.updateCentre(self.centreCoordinate)
        if event.key() == Qt.Key_A:
            self.centreCoordinate = QPointF(-35.09138204, 138.07387413)
            self.mapLayer.updateCentre(self.centreCoordinate)
        if event.key() == Qt.Key_M:
            self.centreCoordinate = QPointF(0, 0)
            self.mapLayer.updateCentre(self.centreCoordinate)

        self.mapLayer.updateCanvasSize(self.canvasSize)