filterView.py 8.64 KB
Newer Older
1
from PyQt5 import QtGui, QtWidgets, QtCore
2 3 4 5 6
import sys
sys.path.append("C://Users//xbrjos//Desktop//Python")
import gepard
from gepard import dataset
import helpers
7
import numpy as np
8 9 10 11 12 13 14 15


class FilterView(QtWidgets.QGraphicsView):

    def __init__(self):
        super(FilterView, self).__init__()
        self.setWindowTitle('FilterView')

16 17
        self.dataset: dataset.DataSet = None

18 19 20 21 22 23 24
        scene = QtWidgets.QGraphicsScene(self)
        scene.setItemIndexMethod(QtWidgets.QGraphicsScene.NoIndex)
        scene.setBackgroundBrush(QtCore.Qt.darkGray)
        self.setScene(scene)
        self.setCacheMode(QtWidgets.QGraphicsView.CacheBackground)
        self.setViewportUpdateMode(QtWidgets.QGraphicsView.BoundingRectViewportUpdate)
        self.setRenderHint(QtGui.QPainter.Antialiasing)
25 26

        self.drag = None
27

28
        self.filter: FilterGraphItem = FilterGraphItem()
29 30
        self.scene().addItem(self.filter)
        self.measuringBoxes: list = []
31
        self.contourItems: list = []
32

33
    def update_measure_boxes(self, topLefts: list, boxSize: float) -> None:
34
        self._remove_measure_boxes()
35 36 37 38 39 40 41
        offset = self.filter.circleOffset
        for x, y in topLefts:
            newBox: MeasureBoxGraphItem = MeasureBoxGraphItem(x+offset[0], y+offset[1], boxSize, boxSize)
            self.measuringBoxes.append(newBox)
            self.scene().addItem(newBox)

        self._update_measured_contours()
42 43 44 45 46 47

    def _remove_measure_boxes(self) -> None:
        for item in self.measuringBoxes:
            self.scene().removeItem(item)
        self.measuringBoxes = []

48
    def load_and_update_from_dataset(self, fname: str) -> None:
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
        try:
            self.dataset = dataset.loadData(fname)
        except IndexError:
            self.dataset = None
            QtWidgets.QMessageBox.critical(self, 'Index Error', 'Unable to load dataset..')

        if self.dataset is not None:
            offset, diameter, widthHeight = helpers.get_filterDimensions_from_dataset(self.dataset)
            offsetx = helpers.convert_length_to_pixels(self.dataset, offset[0])
            offsety = helpers.convert_length_to_pixels(self.dataset, offset[1])
            diameter = helpers.convert_length_to_pixels(self.dataset, diameter)
            width = helpers.convert_length_to_pixels(self.dataset, widthHeight[0])
            height = helpers.convert_length_to_pixels(self.dataset, widthHeight[1])
            self.filter.update_filterSize(width, height, diameter, (offsetx, offsety))
            self._update_particle_contours()
            self._fit_to_window()
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

    def _update_particle_contours(self) -> None:
        self._remove_particle_contours()
        if self.dataset is not None:
            for particle in self.dataset.particleContainer.particles:
                newContour: ParticleContour = ParticleContour(particle.contour)
                self.scene().addItem(newContour)
                self.contourItems.append(newContour)

    def _remove_particle_contours(self) -> None:
        for cntItem in self.contourItems:
            self.scene().removeItem(cntItem)
        self.contourItems = []

    def _update_measured_contours(self) -> None:
80 81
        def distanceToCnt(box: MeasureBoxGraphItem):
            return abs(box.posX - cntStart[0]) + abs(box.posY - cntStart[1])
82 83 84

        for contourItem in self.contourItems:
            contourItem.isMeasured = False
85 86 87 88
            cntStart: tuple = (contourItem.contourData[0, 0, 0], contourItem.contourData[0, 0, 1])
            sortedmeasBoxes = sorted(self.measuringBoxes, key=distanceToCnt)

            for measBox in sortedmeasBoxes:
89 90
                topLeftXY = (measBox.posX, measBox.posY)
                boxWidthHeight = (measBox.width, measBox.height)
91
                if helpers.box_overlaps_contour(topLeftXY, boxWidthHeight, contourItem.contourData):
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
                    contourItem.isMeasured = True
                    contourItem.update()
                    break

    def wheelEvent(self, event: QtGui.QWheelEvent) -> None:
        factor: float = 1.01 ** (event.angleDelta().y() / 8)
        newScale: float = self.filter.scale() * factor
        self.scale(newScale, newScale)

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.MiddleButton:
            self.drag = event.pos()

    def mouseMoveEvent(self, event):
        if self.drag is not None:
            p0 = event.pos()
            move = self.drag - p0
            self.horizontalScrollBar().setValue(move.x() + self.horizontalScrollBar().value())
            self.verticalScrollBar().setValue(move.y() + self.verticalScrollBar().value())

            self.drag = p0

    def mouseReleaseEvent(self, event: QtGui.QMouseEvent) -> None:
        self.drag = None

    def _fit_to_window(self) -> None:
        brect = self.scene().itemsBoundingRect()
        self.fitInView(0, 0, brect.width(), brect.height(), QtCore.Qt.KeepAspectRatio)

121 122 123 124 125

class FilterGraphItem(QtWidgets.QGraphicsItem):
    """
    The Graphical Representation of the actual filter
    """
126
    def __init__(self, filterWidth: float = 500, filterHeight: float = 500, diameter: float = 500):
127
        super(FilterGraphItem, self).__init__()
128 129 130 131
        self.width: float = filterWidth
        self.height: float = filterHeight
        self.diameter: float = diameter
        self.circleOffset: tuple = (0, 0)
132 133
        self.setPos(0, 0)
        self.rect = QtCore.QRectF(0, 0, self.width, self.height)
134
        self.circleRect = QtCore.QRectF(self.circleOffset[0], self.circleOffset[1], self.diameter, self.diameter)
135 136 137 138

    def boundingRect(self) -> QtCore.QRectF:
        return self.rect

139 140 141 142 143 144 145 146 147
    def update_filterSize(self, width: float, height: float, diameter: float, offset: tuple) -> None:
        self.width = width
        self.height = height
        self.rect = QtCore.QRectF(0, 0, self.width, self.height)

        self.diameter = diameter
        self.circleOffset = offset
        self.circleRect = QtCore.QRectF(self.circleOffset[0], self.circleOffset[1], self.diameter, self.diameter)

148 149 150 151 152 153 154
    def paint(self, painter: QtGui.QPainter, option, widget) -> None:
        painter.setPen(QtCore.Qt.black)
        painter.setBrush(QtCore.Qt.white)
        painter.drawRect(self.rect)

        painter.setPen(QtCore.Qt.darkGray)
        painter.setBrush(QtCore.Qt.lightGray)
155
        painter.drawEllipse(self.circleRect)
156 157 158 159 160 161


class MeasureBoxGraphItem(QtWidgets.QGraphicsItem):
    """
    Displays a box in which particles will be measured
    """
162
    def __init__(self, posX: float = 50, posY: float = 50, width: float = 50, height: float = 50) -> None:
163
        super(MeasureBoxGraphItem, self).__init__()
164
        self.setZValue(5)
165 166 167 168 169 170 171 172 173 174 175 176 177
        self.posX: float = posX
        self.posY: float = posY
        self.height: float = height
        self.width: float = width
        self.setPos(posX, posY)
        self.rect = QtCore.QRectF(0, 0, self.width, self.height)
        self.setToolTip(f'x0: {round(self.posX)}, y0: {round(self.posY)}, \n'
                        f'x1: {round(self.posX + self.width)}, y1: {round(self.posY + self.height)}')

    def boundingRect(self) -> QtCore.QRectF:
        return self.rect

    def paint(self, painter, option, widget) -> None:
178
        painter.setBrush(QtGui.QColor(0, 255, 0, 180))
179
        painter.setPen(QtCore.Qt.darkGreen)
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
        painter.drawRects(self.rect)


class ParticleContour(QtWidgets.QGraphicsItem):
    def __init__(self, contourData, pos=(0, 0)) -> None:
        super(ParticleContour, self).__init__()
        self.setZValue(1)
        self.setPos(pos[0], pos[1])
        self.brect: QtCore.QRectF = QtCore.QRectF(0, 0, 1, 1)

        self.isMeasured: bool = False  # Wether the particle overlaps with a measuring box or nt
        self.contourData = contourData
        self.polygon = None

        self.getBrectAndPolygon()

    def getBrectAndPolygon(self) -> None:
        """
        Calculates the bounding rect (needed for drawing the QGraphicsView) and converts the contourdata to a polygon.
        :return:
        """
        self.polygon = QtGui.QPolygonF()
        x0 = self.contourData[:, 0, 0].min()
        x1 = self.contourData[:, 0, 0].max()
        y0 = self.contourData[:, 0, 1].min()
        y1 = self.contourData[:, 0, 1].max()
        for point in self.contourData:
            self.polygon.append(QtCore.QPointF(point[0, 0], point[0, 1]))

        self.brect.setCoords(x0, y0, x1, y1)

    def boundingRect(self) -> QtCore.QRectF:
        return self.brect

    def paint(self, painter, option, widget) -> None:
        if self.polygon is not None:
            if self.isMeasured:
                painter.setPen(QtCore.Qt.darkRed)
                painter.setBrush(QtCore.Qt.red)
            else:
                painter.setPen(QtCore.Qt.darkCyan)
                painter.setBrush(QtCore.Qt.cyan)

            painter.drawPolygon(self.polygon)