Beispiel #1
0
 def generatePicture(self):
     if self.opts["lut"] is None:
         lut = np.empty((len(self.xData), 4), dtype=int)
         pen = self.opts["pen"]
         if isinstance(pen, QPen):
             color = pen.color().getRgb()
         elif len(pen) == 3:
             color = list(pen) + [255]
         else:
             color = pen
         lut[:, :] = color
         self.opts["lut"] = lut
     # generate picture
     self.picture = QPicture()
     p = QPainter(self.picture)
     # if "connect" == "all"
     if isinstance(self.opts["connect"], str):
         lut_array = self.adjustLUT(N_segment=len(self.xData))
         # add to generated picture line by line
         for i, col_values in enumerate(lut_array[:-1]):
             p.setPen(pg.mkPen(col_values))
             p.drawLine(QPointF(self.xData[i], self.yData[i]), QPointF(self.xData[i+1], self.yData[i+1]))
     else:
         lut_array = self.adjustLUT(N_segment=(self.opts["connect"] == 0).sum())
         # add to generated picture with polyline
         polygonF = QPolygonF()
         idx = -1
         for x, y, c in zip(self.xData, self.yData, self.opts["connect"]):
             polygonF.append(QPointF(x, y))
             if c == 0:
                 idx += 1
                 p.setPen(pg.mkPen(lut_array[idx]))
                 p.drawPolyline(polygonF)
                 polygonF = QPolygonF()
Beispiel #2
0
    def paintEvent(self, event):
        rect = QRect(10, 20, 80, 60)

        path = QPainterPath()
        path.moveTo(20, 80)
        path.lineTo(20, 30)
        path.cubicTo(80, 0, 50, 50, 80, 80)

        startAngle = 30 * 16
        arcLength = 120 * 16

        painter = QPainter(self)
        painter.setPen(self.pen)
        painter.setBrush(self.brush)
        if self.antialiased:
            painter.setRenderHint(QPainter.Antialiasing)

        for x in range(0, self.width(), 100):
            for y in range(0, self.height(), 100):
                painter.save()
                painter.translate(x, y)
                if self.transformed:
                    painter.translate(50, 50)
                    painter.rotate(60.0)
                    painter.scale(0.6, 0.9)
                    painter.translate(-50, -50)

                if self.shape == RenderArea.Line:
                    painter.drawLine(rect.bottomLeft(), rect.topRight())
                elif self.shape == RenderArea.Points:
                    painter.drawPoints(RenderArea.points)
                elif self.shape == RenderArea.Polyline:
                    painter.drawPolyline(RenderArea.points)
                elif self.shape == RenderArea.Polygon:
                    painter.drawPolygon(RenderArea.points)
                elif self.shape == RenderArea.Rect:
                    painter.drawRect(rect)
                elif self.shape == RenderArea.RoundedRect:
                    painter.drawRoundedRect(rect, 25, 25, Qt.RelativeSize)
                elif self.shape == RenderArea.Ellipse:
                    painter.drawEllipse(rect)
                elif self.shape == RenderArea.Arc:
                    painter.drawArc(rect, startAngle, arcLength)
                elif self.shape == RenderArea.Chord:
                    painter.drawChord(rect, startAngle, arcLength)
                elif self.shape == RenderArea.Pie:
                    painter.drawPie(rect, startAngle, arcLength)
                elif self.shape == RenderArea.Path:
                    painter.drawPath(path)
                elif self.shape == RenderArea.Text:
                    painter.drawText(rect, Qt.AlignCenter,
                                     "PyQt by\nRiverbank Computing")
                elif self.shape == RenderArea.Pixmap:
                    painter.drawPixmap(10, 10, self.pixmap)

                painter.restore()

        painter.setPen(self.palette().dark().color())
        painter.setBrush(Qt.NoBrush)
        painter.drawRect(QRect(0, 0, self.width() - 1, self.height() - 1))
    def _drawSkel(self, worm_qimg, skel_dat, skel_colors=GOOD_SKEL_COLOURS):

        qPlg = {}
        for tt, dat in skel_dat.items():
            qPlg[tt] = QPolygonF()
            for p in dat:
                #do not add point if it is nan
                if p[0] == p[0]:
                    qPlg[tt].append(QPointF(*p))

        if not qPlg or len(qPlg['skeleton']) == 0:
            return

        pen = QPen()
        pen.setWidth(1)

        painter = QPainter()
        painter.begin(worm_qimg)

        for k, pol_v in qPlg.items():
            color = skel_colors[k]
            pen.setColor(QColor(*color))
            painter.setPen(pen)
            painter.drawPolyline(pol_v)

        pen.setColor(Qt.black)
        painter.setBrush(Qt.white)
        painter.setPen(pen)

        radius = 3
        painter.drawEllipse(qPlg['skeleton'][0], radius, radius)
        painter.drawEllipse(QPointF(0, 0), radius, radius)

        painter.end()
Beispiel #4
0
    def paintEvent(self, event):
        rect = QRect(10, 20, 80, 60)

        path = QPainterPath()
        path.moveTo(20, 80)
        path.lineTo(20, 30)
        path.cubicTo(80, 0, 50, 50, 80, 80)

        startAngle = 30 * 16
        arcLength = 120 * 16

        painter = QPainter(self)
        painter.setPen(self.pen)
        painter.setBrush(self.brush)
        if self.antialiased:
            painter.setRenderHint(QPainter.Antialiasing)

        for x in range(0, self.width(), 100):
            for y in range(0, self.height(), 100):
                painter.save()
                painter.translate(x, y)
                if self.transformed:
                    painter.translate(50, 50)
                    painter.rotate(60.0)
                    painter.scale(0.6, 0.9)
                    painter.translate(-50, -50)

                if self.shape == RenderArea.Line:
                    painter.drawLine(rect.bottomLeft(), rect.topRight())
                elif self.shape == RenderArea.Points:
                    painter.drawPoints(RenderArea.points)
                elif self.shape == RenderArea.Polyline:
                    painter.drawPolyline(RenderArea.points)
                elif self.shape == RenderArea.Polygon:
                    painter.drawPolygon(RenderArea.points)
                elif self.shape == RenderArea.Rect:
                    painter.drawRect(rect)
                elif self.shape == RenderArea.RoundedRect:
                    painter.drawRoundedRect(rect, 25, 25, Qt.RelativeSize)
                elif self.shape == RenderArea.Ellipse:
                    painter.drawEllipse(rect)
                elif self.shape == RenderArea.Arc:
                    painter.drawArc(rect, startAngle, arcLength)
                elif self.shape == RenderArea.Chord:
                    painter.drawChord(rect, startAngle, arcLength)
                elif self.shape == RenderArea.Pie:
                    painter.drawPie(rect, startAngle, arcLength)
                elif self.shape == RenderArea.Path:
                    painter.drawPath(path)
                elif self.shape == RenderArea.Text:
                    painter.drawText(rect, Qt.AlignCenter,
                            "PyQt by\nRiverbank Computing")
                elif self.shape == RenderArea.Pixmap:
                    painter.drawPixmap(10, 10, self.pixmap)

                painter.restore()

        painter.setPen(self.palette().dark().color())
        painter.setBrush(Qt.NoBrush)
        painter.drawRect(QRect(0, 0, self.width() - 1, self.height() - 1))
Beispiel #5
0
 def image(self):
     pixmap = QPixmap(250, 250)
     pixmap.fill(Qt.transparent)
     painter = QPainter(pixmap)
     painter.setPen(QPen(Qt.black, 8))
     painter.translate(125, 125)
     painter.drawPolyline(self.myPolygon)
     return pixmap
Beispiel #6
0
 def paintEvent(self, QPaintEvent):
     painter = QPainter()
     painter.begin(self)
     pen = QPen(Qt.black, 2, Qt.SolidLine)
     painter.setPen(pen)
     for points in self.points_list:
         painter.drawPolyline(QPolygon(points))
     painter.end()
Beispiel #7
0
 def paint(self,
           painter: QtGui.QPainter,
           option: QStyleOptionGraphicsItem,
           widget: typing.Optional[QWidget] = ...) -> None:
     painter.setRenderHint(QPainter.Antialiasing)
     painter.setPen(self.pen())
     painter.drawPolyline(self.polygon())
     self.paint_poly_points(painter)
Beispiel #8
0
 def image(self):
     pixmap = QPixmap(250, 250)
     pixmap.fill(Qt.transparent)
     painter = QPainter(pixmap)
     painter.setPen(QPen(Qt.black, 8))
     painter.translate(125, 125)
     painter.drawPolyline(self.myPolygon)
     return pixmap
Beispiel #9
0
    def draw(self, image):
        qp = QPainter(image)

        qp.setPen(QPen(self.drawContext.stroke, self.drawContext.width))
        qp.drawPolyline(QPolygon(self.points))

        qp.setPen(QPen(Qt.transparent, 0))
        qp.setBrush(self.drawContext.fill)
        qp.drawPolygon(QPolygon(self.points))
Beispiel #10
0
 def paintEvent(self, event):
     QWidget.paintEvent(self, event)
     width, height = self.width(), self.height()
     polygon = QPolygon()
     for i, rate in enumerate(self.loads):
         x = width - i * self.pointDistance
         y = height - rate * height
         if x < self.boxWidth:
             break
         polygon.append(QPoint(x, y))
     painter = QPainter(self)
     pen = QPen()
     pen.setColor(Qt.darkGreen)
     painter.setPen(pen)
     painter.setRenderHint(QPainter.Antialiasing, True)
     #画网格
     painter.setOpacity(0.5)
     gridSize = self.pointDistance * 4
     deltaX = (width - self.boxWidth) % gridSize + self.boxWidth
     deltaY = height % gridSize
     for i in range(int(width / gridSize)):
         x = deltaX + gridSize * i
         painter.drawLine(x, 0, x, height)
     for j in range(int(height / gridSize)):
         y = j * gridSize + deltaY
         painter.drawLine(self.boxWidth, y, width, y)
     #画折线
     pen.setColor(Qt.darkCyan)
     pen.setWidth(2)
     painter.setPen(pen)
     painter.setOpacity(1)
     painter.drawPolyline(polygon)
     #画展示框
     if len(self.loads) > 0:
         rate = self.loads[0]
     else:
         rate = 1.0
     rect1 = QRect(4, height * 0.05, self.boxWidth - 9, height * 0.7)
     rect2 = QRect(4, height * 0.8, self.boxWidth - 9, height * 0.2)
     centerX = int(rect1.width() / 2) + 1
     pen.setWidth(1)
     for i in range(rect1.height()):
         if i % 4 == 0:
             continue
         if (rect1.height() - i) / rect1.height() > rate:
             pen.setColor(Qt.darkGreen)
         else:
             pen.setColor(Qt.green)
         painter.setPen(pen)
         for j in range(rect1.width()):
             if centerX - 1 <= j <= centerX + 1:
                 continue
             painter.drawPoint(rect1.x() + j, rect1.y() + i)
     pen.setColor(Qt.black)
     painter.setPen(pen)
     painter.drawText(rect2, Qt.AlignHCenter | Qt.AlignVCenter, str(int(rate * 100)) + "%")
Beispiel #11
0
    def create_inner_and_outer_mask(self):
        '''
        Based on the traces, this function creates two masks: One ('inner_mask') to mark all pixels inside the shape
        as defined by the traces,  and one mask, 'outer_mask' to mark the pixels outside the shape defined by the traces
        :return: inner_mask and outer_mask: Two boolean masks
        '''

        # use the same method to draw the traces
        pixmap = QPixmap(self.slice_photo.size())
        pixmap.fill(QColor(255, 255, 255))
        painter = QPainter()
        painter.begin(pixmap)
        pen = QPen()
        pen.setWidth(self.pen_width)
        pen.setBrush(Qt.black)
        pen.setCapStyle(Qt.RoundCap)
        painter.setPen(pen)
        for trace in self.traces:
            painter.drawPolyline(QPolygon(trace))
        painter.end()
        # that is us done painting
        #convert the Qpixmap into a numpy array
        arr = self.get_np_array(pixmap)
        # find the center
        arr = np.mean(arr, axis=-1, dtype=np.uint8)
        l = []
        for trace in self.traces:
            l = l + [[p.x(), p.y()] for p in trace]
        center = np.mean(np.array(l), axis=0, dtype=np.int)

        # fill the shape ( using floodfill)  starting from the center
        inner_mask = arr.copy()
        h, w = inner_mask.shape[:2]
        mask = np.zeros((h + 2, w + 2), np.uint8)
        cv2.floodFill(inner_mask, mask, (center[0], center[1]), 128)

        #and calculate the masks
        inner_mask = (inner_mask > 100).astype(np.bool)
        middle_mask = (arr < 32).astype(np.bool)
        outer_mask = np.logical_and(~inner_mask, ~middle_mask)

        # for debugging purposes, create a matplotlib image (only visible in IDE)
        fig, axs = plt.subplots(2, 2)
        axs[0, 0].imshow(arr)
        axs[0, 1].imshow(middle_mask)
        axs[1, 0].imshow(inner_mask)
        axs[1, 1].imshow(outer_mask)

        for axh in axs:
            for ax in axh:
                ax.set_aspect('equal')
        fig.tight_layout()
        plt.show()

        return inner_mask, outer_mask
Beispiel #12
0
 def paintEvent(self, event):
     painter = QPainter(self)
     pixmap = QPixmap(self.image)
     painter.drawPixmap(self.rect(), pixmap)
     pen1 = QPen(Qt.red, 1)
     painter.setPen(pen1)
     if self.hide == False:
         painter.drawPolyline(self.poly1)
     pen2 = QPen(Qt.yellow, 1)
     painter.setPen(pen2)
     if self.hide == False:
         painter.drawPolyline(self.poly2)
Beispiel #13
0
    def paintEvent(self, event):
        painter = QPainter(self)

        # complete graph ratio
        scale, translation = self._get_scale_translation()

        if self.need_draw_grid:
            self.draw_grid(scale, translation)

        painter.drawPixmap(QPoint(), self.pixmap)

        ############ EXTERIOR #################################
        painter.setPen(self.external_contour_pen)
        exterior_coords_on_screen = [
            QPoint(*tuple(p * scale + translation))
            for p in self.current_polygon_exterior
        ]
        painter.drawPolyline(QPolygon(exterior_coords_on_screen))

        ############ INTERIOR #################################
        painter.setPen(self.internal_contour_pen)
        interior_coords_list = []
        for current_polygon_interior in self.current_polygon_interiors:
            interior_coords_on_screen = [
                QPoint(*tuple(p * scale + translation))
                for p in current_polygon_interior
            ]
            painter.drawPolyline(QPolygon(interior_coords_on_screen))
            interior_coords_list.append(interior_coords_on_screen)

        ####################### Points of each point ##########
        # Draw selected Point in different color
        if self.current_selected_tuple is not None and self.current_selected_tuple[
                0] == 'exterior':
            exterior_coords_on_screen = self.draw_exterior_selected_point(
                exterior_coords_on_screen, painter)

        if self.current_selected_tuple is not None and self.current_selected_tuple[
                0] == 'interior':
            interior_coords_list = self.draw_interior_selected_point(
                interior_coords_list, painter)

        painter.setPen(self.external_point_pen)
        painter.drawPoints(QPolygon(exterior_coords_on_screen))

        painter.setPen(self.internal_point_pen)
        for interior_coord in interior_coords_list:
            painter.drawPoints(QPolygon(interior_coord))

        ###################### Each tile in the solution ###############
        if self.current_best_solution is not None:
            self.draw_solution(painter)
Beispiel #14
0
	def update_pixmap(self, size, convert_to_gui_point):
		print('updating pixmap')
		pixmap = QPixmap(size)
		pixmap.fill(QColor(255, 255, 255, 0))
		qp = QPainter()
		qp.begin(pixmap)

		if self.display_line or self.display_points:
			x_data, y_data = self.get_data()

			line_points = np.dstack(convert_to_gui_point([np.array(x_data), np.array(y_data)]))[0]
			if self.sort_by_x:
				line_points = line_points[line_points[:,0].argsort()]
			qpoints = [QPoint(e[0], e[1]) for e in line_points]

			if self.display_line and len(line_points) > 0:
				pen = QPen()
				pen.setStyle(self.line_style)
				pen.setCapStyle(Qt.RoundCap)
				if self.line_style is Qt.CustomDashLine and self.line_pattern:
					pen.setDashPattern(self.line_pattern)
				pen.setColor(self.line_colour)
				pen.setWidth(self.line_width)
				qp.setPen(pen)
				qp.drawPolyline(*qpoints)  # if self.is_point_visible(e)])

			if self.display_points:
				pen = QPen()
				pen.setColor(self.point_colour)

				if self.point_shape is PointShape.CIRCLE:
					pen.setWidth(self.point_size / 10)
					pen.setCapStyle(Qt.RoundCap)
					draw_func = lambda painter, point: painter.drawPoint(point)
				elif self.point_shape is PointShape.SQUARE:
					pen.setWidth(self.point_size / 10)
					pen.setCapStyle(Qt.SquareCap)
					draw_func = lambda painter, point: painter.drawPoint(point)
				elif self.point_shape is PointShape.RING:
					pen.setWidth(self.point_size / 40)
					draw_func = lambda painter, point: painter.drawEllipse(point, self.point_size / 20, self.point_size / 20)
				else:
					draw_func = print

				qp.setPen(pen)
				for pnt in qpoints:
					draw_func(qp, pnt)

		qp.end()
		self._pixmap = pixmap
		return self._pixmap
Beispiel #15
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setPen(Qt.NoPen)
        painter.setBrush(Qt.white)
        painter.drawRect(self.rect())

        painter.setPen(Qt.black)

        # draw historical points
        for points in self.psets:
            painter.drawPolyline(*points)

        # draw current points
        if self.points:
            painter.drawPolyline(*self.points)
Beispiel #16
0
    def drawSkel(self, worm_img, worm_qimg, row_data, roi_corner = (0,0)):
        if not self.skel_file or not isinstance(self.trajectories_data, pd.DataFrame):
            return

        c_ratio_y = worm_qimg.width()/worm_img.shape[1];
        c_ratio_x = worm_qimg.height()/worm_img.shape[0];
        
        skel_id = int(row_data['skeleton_id'])

        qPlg = {}

        with tables.File(self.skel_file, 'r') as ske_file_id:
            for tt in ['skeleton', 'contour_side1', 'contour_side2']:
                dat = ske_file_id.get_node('/' + tt)[skel_id];
                dat[:,0] = (dat[:,0]-roi_corner[0])*c_ratio_x
                dat[:,1] = (dat[:,1]-roi_corner[1])*c_ratio_y
            
                qPlg[tt] = QPolygonF()
                for p in dat:
                    qPlg[tt].append(QPointF(*p))
        
        if 'is_good_skel' in row_data and row_data['is_good_skel'] == 0:
            self.skel_colors = {'skeleton':(102, 0, 0 ), 
            'contour_side1':(102, 0, 0 ), 'contour_side2':(102, 0, 0 )}
        else:
            self.skel_colors = {'skeleton':(27, 158, 119 ), 
            'contour_side1':(217, 95, 2), 'contour_side2':(231, 41, 138)}

        pen = QPen()
        pen.setWidth(2)
        
        painter = QPainter()
        painter.begin(worm_qimg)
    
        for tt, color in self.skel_colors.items():
            pen.setColor(QColor(*color))
            painter.setPen(pen)
            painter.drawPolyline(qPlg[tt])
        
        pen.setColor(Qt.black)
        painter.setBrush(Qt.white)
        painter.setPen(pen)
    
        radius = 3
        painter.drawEllipse(qPlg['skeleton'][0], radius, radius)

        painter.end()
Beispiel #17
0
    def paintEvent(self, QPaintEvent):
        p = QPainter(self)
        p.setPen(self.pen)
        p.setBrush(self.brush)

        rect = QRect(50, 100, 300, 200)
        points = [
            QPoint(150, 100),
            QPoint(300, 150),
            QPoint(350, 250),
            QPoint(100, 300)
        ]
        startAngle = 30 * 16
        spanAngle = 120 * 16

        path = QPainterPath()
        path.addRect(150, 150, 100, 100)
        path.moveTo(100, 100)
        path.cubicTo(300, 100, 200, 200, 300, 300)
        path.cubicTo(100, 300, 200, 200, 100, 100)

        if self.shape == "Line":
            p.drawLine(rect.topLeft(), rect.bottomRight())
        elif self.shape == "Rectangle":
            p.drawRect(rect)
        elif self.shape == 'Rounded Rectangle':
            p.drawRoundedRect(rect, 25, 25, Qt.RelativeSize)
        elif self.shape == "Ellipse":
            p.drawEllipse(rect)
        elif self.shape == "Polygon":
            p.drawPolygon(QPolygon(points), Qt.WindingFill)
        elif self.shape == "Polyline":
            p.drawPolyline(QPolygon(points))
        elif self.shape == "Points":
            p.drawPoints(QPolygon(points))
        elif self.shape == "Pie":
            p.drawPie(rect, startAngle, spanAngle)
        elif self.shape == "Arc":
            p.drawArc(rect, startAngle, spanAngle)
        elif self.shape == "Chord":
            p.drawChord(rect, startAngle, spanAngle)
        elif self.shape == "Path":
            p.drawPath(path)
        elif self.shape == "Text":
            p.drawText(rect, Qt.AlignCenter, "Hello Qt!")
        elif self.shape == "Pixmap":
            p.drawPixmap(150, 150, QPixmap("images/qt-logo.png"))
Beispiel #18
0
 def updateColor(self, item):
     pixmap = QPixmap(16, 16)
     color = QColor()
     # if item:
     #     color = item.backgroundColor()
     if not color.isValid():
         color = self.palette().base().color()
     painter = QPainter(pixmap)
     painter.fillRect(0, 0, 16, 16, color)
     lighter = color.lighter()
     painter.setPen(lighter)
     # light frame
     painter.drawPolyline(QPoint(0, 15), QPoint(0, 0), QPoint(15, 0))
     painter.setPen(color.darker())
     # dark frame
     painter.drawPolyline(QPoint(1, 15), QPoint(15, 15), QPoint(15, 1))
     painter.end()
Beispiel #19
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setPen(Qt.red)

        painter.drawLine(10, 10, 100, 140)

        painter.setPen(Qt.blue)
        painter.drawRect(120, 10, 80, 80)

        rectf = QRectF(230.0, 10.0, 80.0, 80.0)
        painter.drawRoundedRect(rectf, 20, 20)

        p1 = [QPoint(10, 100), QPoint(220, 110), QPoint(220, 190)]
        painter.drawPolyline(QPolygon(p1))

        p2 = [QPoint(120, 110), QPoint(220, 110), QPoint(220, 190)]
        painter.drawPolygon(QPolygon(p2))
Beispiel #20
0
 def updateColor(self, item):
     pixmap = QPixmap(16, 16)
     color = QColor()
     if item:
         color = item.backgroundColor()
     if not color.isValid():
         color = self.palette().base().color()
     painter = QPainter(pixmap)
     painter.fillRect(0, 0, 16, 16, color)
     lighter = color.lighter()
     painter.setPen(lighter)
     # light frame
     painter.drawPolyline(QPoint(0, 15), QPoint(0, 0), QPoint(15, 0))
     painter.setPen(color.darker())
     # dark frame
     painter.drawPolyline(QPoint(1, 15), QPoint(15, 15), QPoint(15, 1))
     painter.end()
     self.colorAction.setIcon(QIcon(pixmap))
Beispiel #21
0
    def paintEvent(self, event):

        painter = QPainter()
        painter.begin(self)
        painter.fillRect(event.rect(), QBrush(Qt.white))
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setPen(QPen(QBrush(Qt.red), 1, Qt.DashLine))
        painter.drawRect(self.largest_rect)
        painter.setPen(QPen(Qt.black))
        painter.drawRect(self.clip_rect)
        for i in range(4):
            painter.drawRect(self.corner(i))

        painter.setClipRect(self.clip_rect)
        painter.drawPolyline(self.polygon)
        painter.setBrush(QBrush(Qt.blue))
        painter.drawPath(self.path)
        painter.end()
    def drawThreshMask(self, worm_img, worm_qimg, row_data, read_center=True):
        #in very old versions of the tracker I didn't save the area in trajectories table,
        #let's assign a default value to deal with this cases
        if 'area' in row_data:
            min_blob_area = row_data['area'] / 2
        else:
            min_blob_area = 10

        c1, c2 = (row_data['coord_x'],
                  row_data['coord_y']) if read_center else (-1, -1)

        worm_mask, worm_cnt, _ = getWormMask(
            worm_img,
            row_data['threshold'],
            strel_size=self.strel_size,
            roi_center_x=c1,
            roi_center_y=c2,
            min_blob_area=min_blob_area,
            is_light_background=self.is_light_background)

        worm_mask = QImage(worm_mask.data, worm_mask.shape[1],
                           worm_mask.shape[0], worm_mask.strides[0],
                           QImage.Format_Indexed8)
        worm_mask = worm_mask.convertToFormat(QImage.Format_RGB32,
                                              Qt.AutoColor)
        worm_mask = QPixmap.fromImage(worm_mask)

        worm_mask = worm_mask.createMaskFromColor(Qt.black)
        p = QPainter(worm_qimg)
        p.setPen(QColor(0, 204, 102))
        p.drawPixmap(worm_qimg.rect(), worm_mask, worm_mask.rect())

        if False:
            #test skeletonization
            skeleton, ske_len, cnt_side1, cnt_side2, cnt_widths, cnt_area = \
                getSkeleton(worm_cnt, np.zeros(0), 49)
            for cnt in skeleton, cnt_side1, cnt_side2:
                p.setPen(Qt.black)
                polyline = QPolygonF()
                for point in cnt:
                    polyline.append(QPointF(*point))
                p.drawPolyline(polyline)

        p.end()
Beispiel #23
0
    def draw_food_contour(self, image):
        if self.food_coordinates is None or not self.ui.checkBox_showFood.isChecked():
            return

        painter = QPainter()
        painter.begin(image)

        penwidth = max(1, max(image.height(), image.width()) // 800)
        col = Qt.darkMagenta
        p = QPolygonF()
        for x,y in self.food_coordinates:
            p.append(QPointF(x,y))

        pen = QPen()
        pen.setWidth(penwidth)
        pen.setColor(col)
        painter.setPen(pen)

        painter.drawPolyline(p)
        painter.end()
Beispiel #24
0
    def plot(self, frame_number, image):
        if self.frames_data is None:
            return

        if not frame_number in self.cnt_per_frame:
            return

        painter = QPainter()
        painter.begin(image)

        penwidth = max(1, max(image.height(), image.width()) // 800)
        pen = QPen()
        pen.setWidth(penwidth)

        frame_data = self.frames_data.loc[self.cnt_per_frame[frame_number]]

        for _, row in frame_data.iterrows():
            interface_id = row['interface_id']
            cnt_id = row['contour_id']

            if not cnt_id in self.coord_per_cnt:
                continue

            coords = self.coords_data.loc[self.coord_per_cnt[cnt_id]]
            xx = coords['X']
            yy = coords['Y']

            if not interface_id in self.traj_colors:
                self.traj_colors[interface_id] = QColor(
                    *np.random.randint(50, 230, 3))
            col = self.traj_colors[interface_id]

            p = QPolygonF()
            for x, y in zip(xx, yy):
                p.append(QPointF(x, y))

            pen.setColor(col)
            painter.setPen(pen)
            painter.drawPolyline(p)

        painter.end()
Beispiel #25
0
    def paint(self, painter: gui.QPainter, option: qt.QStyleOptionGraphicsItem, widget: Optional[qt.QWidget] = ...):
        color = gui.QColor(255, 0, 0, 255)
        if self.dragging:
            color.setAlphaF(0.7)
        if self._selected:
            color.setGreen(200)
        if self._drawing:
            color = gui.QColor(120, 32, 32, 100)
        self._pen.setColor(color)
        painter.setPen(self._pen)

        arrow = gui.QPolygonF()
        arrow.append(qtc.QPointF(0, 10))
        arrow.append(qtc.QPointF(0, -10))
        arrow.append(qtc.QPointF(self.length - 50, -10))
        arrow.append(qtc.QPointF(self.length - 50, -20))
        arrow.append(qtc.QPointF(self.length, 0))
        arrow.append(qtc.QPointF(self.length - 50, 20))
        arrow.append(qtc.QPointF(self.length - 50, 10))
        arrow.append(qtc.QPointF(0, 10))
        painter.drawPolyline(arrow)
Beispiel #26
0
    def paintEvent(self, event):
        painter = QPainter(self)

        print(self.curves)
        for curve_name in self.curves:
            self.curves[curve_name].make_plot(self.width(), self.height())
            if self.activeCurve != curve_name:
                painter.setPen(QPen(QColor(120, 120, 120)))
                painter.drawPolyline(self.curves[curve_name].plot)

        if self.activeCurve is not None:
            print(self.curves[self.activeCurve].points)
            if self.curves[self.activeCurve].is_guide:
                painter.setPen(QPen(QColor(255, 0, 0)))
                painter.drawPolyline(self.curves[self.activeCurve].guide)
            #  potem aktywna
            painter.setPen(QPen(QColor(0, 0, 0)))
            print(self.curves[self.activeCurve].plot)
            painter.drawPolyline(self.curves[self.activeCurve].plot)

            #  potem zaznaczone punkty
            if self.pointSelected is not None:
                painter.setPen(QPen(QColor(255, 0, 0)))
                x, y = self.curves[self.activeCurve].points[self.pointSelected]
                painter.drawRect(self.width() * x, self.height() * y, 10, 10)

            #  i same punkty
            painter.setPen(QPen(QColor(0, 0, 0)))
            painter.setBrush(QBrush(QColor(0, 154, 0)))
            for (i, (x, y)) in enumerate(self.curves[self.activeCurve].points):
                painter.drawEllipse(self.width() * x,
                                    self.height() * y, 10, 10)
                painter.drawText(self.width() * x + 10,
                                 self.height() * y + 20, str(i))
Beispiel #27
0
    def paintEvent(self, event):
        qp = QPainter()
        pen = QPen()
        qp.begin(self)
        qp.setRenderHint(QPainter.Antialiasing)


        for path in self.paths:
            pen.setColor(path[1])
            pen.setWidth(path[2])
            qp.setPen(pen)
            qp.drawPolyline(path[0])

        pen.setColor(self.color)
        pen.setWidth(self.width)
        qp.setPen(pen)
        qp.drawPolyline(self.current)

        pen.setColor(QColor("orange"))
        qp.setPen(pen)
        for path in self.selected_poly:
            qp.drawPolyline(path[0])
        pen.setStyle(Qt.DashDotLine)
        pen.setColor(QColor("black"))
        pen.setWidth(2)
        qp.setPen(pen)
        qp.drawPolygon(self.select)

        qp.end()
Beispiel #28
0
    def _draw_food_contour(self, image):
        if self.food_coordinates is None or not self.ui.checkBox_showFood.isChecked(
        ):
            return

        painter = QPainter()
        painter.begin(image)

        penwidth = max(1, max(image.height(), image.width()) // 800)
        self.img_h_ratio = image.height() / self.image_height
        self.img_w_ratio = image.width() / self.image_width

        col = QColor(255, 0, 0)
        p = QPolygonF()
        for x, y in self.food_coordinates:
            p.append(QPointF(x, y))

        pen = QPen()
        pen.setWidth(penwidth)
        pen.setColor(col)
        painter.setPen(pen)

        painter.drawPolyline(p)
        painter.end()
 def paintEvent(self, event):
     painter = QPainter(self)
     painter.setOpacity(self._opacity)
     painter.setRenderHint(QPainter.Antialiasing, True)
     painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
     painter.save()
     pen = QPen(Qt.DashLine)
     pen.setWidthF(0.5)
     pen.setColor(Qt.white)
     painter.setPen(pen)
     c = QPoint(self.off, self.height() * 0.6)
     painter.drawPolyline(self._sw1.p1, c)
     painter.drawPolyline(self._sw1.p3, c)
     painter.drawPolyline(c, self._sw2.p8)
     painter.restore()
     pen = QPen(Qt.SolidLine)
     pen.setWidthF(0.5)
     pen.setColor(Qt.white)
     painter.setPen(pen)
     painter.drawPolyline(self._sw1.p2, self._sw1.p8)
     painter.drawPolyline(self._sw1.p7, self._sw1.p8)
     painter.drawPolyline(self._sw1.p8, self._sw1.p9)
Beispiel #30
0
 def draw(self, painter: QPainter):
     if len(self.points) > 1:
         painter.setPen(self._pen)
         painter.setBrush(self._brush)
         if self.pos is not None:
             nPoints = len(self.points)
             points = []
             for i in range(nPoints):
                 points.append([
                     self.points[i][0] + self.pos[0],
                     self.points[i][1] + self.pos[1]
                 ])
         else:
             points = self.points
         if self.form == Shape.RECTANGLE:
             x1, y1 = points[0]
             x2, y2 = points[1]
             painter.drawRect(x1, y1, x2 - x1, y2 - y1)
         elif self.form == Shape.ELLIPSE:
             x1, y1 = points[0]
             x2, y2 = points[1]
             painter.drawEllipse(x1, y1, x2 - x1, y2 - y1)
         elif self.form == Shape.POLYGON:
             poly = QPolygon()
             for point in points:
                 poly << QPoint(point[0], point[1])
             if not self.drawing:
                 painter.drawPolygon(poly)
             else:
                 painter.drawPolyline(poly)
         elif self.form == Shape.POLYLINE:
             poly = QPolygon()
             for point in points:
                 poly << QPoint(point[0], point[1])
             painter.drawPolyline(poly)
         elif self.form == Shape.LINE:
             poly = QPolygon()
             for point in points[0:2]:
                 poly << QPoint(point[0], point[1])
             painter.drawPolyline(poly)
Beispiel #31
0
	def paintEvent(self, event):
		rect = QRect(10, 20, 80, 60)
  
		path = QPainterPath()
		path.moveTo(20, 80)
		path.lineTo(20, 30)
		path.cubicTo(80, 0, 50, 50, 80, 80)
  
		startAngle = 30 * 16
		arcLength = 120 * 16
  
		painter = QPainter(self)
		painter.setPen(self.pen)
		painter.setBrush(self.brush)
		if self.antialiased:
			painter.setRenderHint(QPainter.Antialiasing)

		angle_step = 360 / self.n_states

		painter.save()
		painter.translate(self.dist_center.x(), self.dist_center.y())

		#painter.drawRect(- self.dist_radius, - self.dist_radius, self.dist_radius *2,self.dist_radius*2)
		#painter.drawEllipse(QPoint(0, 0), self.dist_radius , self.dist_radius)
		painter.rotate(-180)	#to start painting from the left side of the circle
		x = self.dist_radius * math.cos(0)
		y = self.dist_radius * math.sin(0)

		for h in range(self.n_states):

			rot = angle_step * h

			painter.save()
			painter.rotate(rot)
			painter.translate(x,y)

			if self.machine.getState(h).isActive():
				painter.setBrush(self.greenGradientBrush)			
			painter.drawEllipse(QPoint(0,0), self.state_radius, self.state_radius)
			#global position of transformed coordinates
			gx = painter.worldTransform().map(QPoint(0,0)).x()
			gy = painter.worldTransform().map(QPoint(0,0)).y()
			self.machine.getState(h).setPos(gx, gy)

			# text transformation
			painter.save()
			painter.rotate(180)
			painter.rotate(-rot)
			font = painter.font();
			font.setPixelSize(self.state_radius*.4);
			painter.setFont(font);
			rect = QRect(-self.state_radius, -self.state_radius, self.state_radius*2, self.state_radius*2)
			painter.drawText(rect, Qt.AlignCenter, self.machine.getState(h).getName());
			painter.restore()
			#end text transformation


			painter.restore()			
			
		painter.restore()

		
		#drawing transitions.
		painter.save()
		pptv = QTransform()
		pptv.translate(0, self.height())
		pptv.rotate(-180, Qt.XAxis)
		painter.setTransform(pptv)
		s = self.machine.getStates()
		for j in s:
			t = j.getTransitions()
			for i in t:
				#get the points in the canvas
				init = QPoint(j.getPos()[0], j.getPos()[1])
				end = QPoint(self.machine.getState(i.getStateEnd()).getPos()[0], self.machine.getState(i.getStateEnd()).getPos()[1])
				# get the transformed ponts
				init2 = QPoint(painter.worldTransform().map(init))
				end2 = QPoint(painter.worldTransform().map(end))

				#get the angle between states centers
				angle = math.atan2(end2.y() - init2.y(), end2.x() - init2.x())

				#get the coordinates of the starting point of the transition (it starts in the bound, not in the center)
				newX = self.state_radius * math.cos(angle) + init2.x()
				newY = self.state_radius * math.sin(angle) + init2.y()
				init2.setX(newX)
				init2.setY(newY)

				#same for the end of the transition
				angle2 = math.atan2(init2.y() - end2.y(), init2.x() - end2.x())
				newX2 = self.state_radius * math.cos(angle2) + end2.x()
				newY2 = self.state_radius * math.sin(angle2) + end2.y()
				end2.setX(newX2)
				end2.setY(newY2)

				#painter.drawLine(init, end)
				painter.drawLine(init2, end2)
				init = QPoint(painter.worldTransform().map(init2))
				end = QPoint(painter.worldTransform().map(end2))
				i.setOrig(init.x(), init.y())
				i.setDest(end.x(), end.y())	
				i.setAngle(angle)
				#painter.draw
		painter.restore()

		painter.setPen(QPen(QColor(Qt.gray), 3))
		for i in machine.getStates():
			for j in i.getTransitions():
				i = QPoint(j.getOrig()[0], j.getOrig()[1])
				o = QPoint(j.getDest()[0], j.getDest()[1])			
				painter.drawPolyline(i, o)

				painter.save()
				painter.setPen(QPen(QColor(Qt.gray), 2))
				painter.translate(j.getDest()[0],j.getDest()[1])
				painter.rotate(90 - j.getAngle()*180/math.pi)
				a = QPoint(0,0)
				b = QPoint(-5,10)
				c = QPoint(5,10)

				a1 = painter.worldTransform().map(a)
				b1 = painter.worldTransform().map(b)
				c1 = painter.worldTransform().map(c)
				pointer = QPolygon([a,b,c])
				painter.drawPolygon(pointer)
				painter.restore()

				painter.save()
				if j.isActive():

					t = self.machine.getTransition(self.t_active)
					init = QPoint(t.getOrig()[0], t.getOrig()[1])
					end = QPoint(t.getDest()[0], t.getDest()[1])
					
					painter.setPen(QPen(QColor(Qt.green), 3))
					painter.drawPolyline(init, end)
					
					
					painter.setPen(QPen(QColor(Qt.gray), 3))
					painter.drawPolyline(self.poly(self.pts))

					painter.setBrush(QBrush(QColor(255, 0, 0)))
					painter.setPen(QPen(QColor(Qt.red), 2))
					pointer = QPolygon([a1,b1,c1])
					painter.drawPolygon(pointer)

					painter.setBrush(QBrush(QColor(255, 0, 0)))
					painter.setPen(QPen(QColor(Qt.black), 1))
				painter.restore()

					
					#Ball that follows the line
					#for x, y in self.pts:
						#painter.drawEllipse(QRectF(x - 4, y - 4, 8, 8))

				painter.save()
				pptv = QTransform()
				painter.setPen(QPen(QColor(Qt.black), 3))
				middleX = (j.getOrig()[0] + j.getDest()[0]) /2
				middleY = (j.getOrig()[1] + j.getDest()[1]) /2
				pptv.translate(middleX, middleY)
				#pptv.rotate(-j.getAngle()*180/math.pi)
				painter.setTransform(pptv)
				font = painter.font();
				font.setPixelSize(self.state_radius*.3);
				painter.setFont(font);
				rect = QRect(-self.state_radius, -self.state_radius, self.state_radius*2, self.state_radius*2)
				name = str(j.getId())+ '. ' + j.getName()
				painter.drawText(rect, Qt.AlignCenter, name)
				painter.restore()


  
		painter.setPen(self.palette().dark().color())
		painter.setBrush(Qt.NoBrush)
		painter.drawRect(QRect(0, 0, self.width() - 1, self.height() - 1))
Beispiel #32
0
class Renderer:
    def __init__(self, width, height, ownWindow=False):
        self.width = width
        self.height = height

        self.img = QImage(width, height, QImage.Format_RGB888)
        self.painter = QPainter()

        self.window = None
        if ownWindow:
            self.app = QApplication([])
            self.window = Window()

    def close(self):
        """
        Deallocate resources used
        """
        pass

    def beginFrame(self, shape_map, positions):
        self.bytesPerLine = 3 * self.im_np.shape[1]
        self.img = QImage(shape_map, shape_map.shape[0], shape_map.shape[1], bytesPerLine, QImage.Format_RGB888)
        self.painter.begin(self.img)
        self.painter.setRenderHint(QPainter.Antialiasing, False)
        # Clear the background
        self.qrect = []
        self.painter.setBrush(QColor(1, 1, 1))
        for p in positions:
            self.qrect.append(QRect(p[0], p[1], 5, 5))
            self.painter.drawRect(self.qrect[-1])

    def endFrame(self):
        self.painter.end()

        if self.window:
            if self.window.closed:
                self.window = None
            else:
                self.window.setPixmap(self.getPixmap())
                self.app.processEvents()

    def getPixmap(self):
        return QPixmap.fromImage(self.img)

    def getArray(self):
        """
        Get a numpy array of RGB pixel values.
        The array will have shape (height, width, 3)
        """

        numBytes = self.width * self.height * 3
        buf = self.img.bits().asstring(numBytes)
        output = np.frombuffer(buf, dtype='uint8')
        output = output.reshape((self.height, self.width, 3))

        return output

    def push(self):
        self.painter.save()

    def pop(self):
        self.painter.restore()

    def rotate(self, degrees):
        self.painter.rotate(degrees)

    def translate(self, ind, x, y):
        self.qrect[ind].translate(x, y)
        self.window.update()

    def scale(self, x, y):
        self.painter.scale(x, y)

    def setLineColor(self, r, g, b, a=255):
        self.painter.setPen(QColor(r, g, b, a))

    def setColor(self, r, g, b, a=255):
        self.painter.setBrush(QColor(r, g, b, a))

    def setLineWidth(self, width):
        pen = self.painter.pen()
        pen.setWidthF(width)
        self.painter.setPen(pen)

    def drawLine(self, x0, y0, x1, y1):
        self.painter.drawLine(x0, y0, x1, y1)

    def drawCircle(self, x, y, r):
        center = QPoint(x, y)
        self.painter.drawEllipse(center, r, r)

    def drawPolygon(self, points):
        """Takes a list of points (tuples) as input"""
        points = map(lambda p: QPoint(p[0], p[1]), points)
        self.painter.drawPolygon(QPolygon(points))

    def drawPolyline(self, points):
        """Takes a list of points (tuples) as input"""
        points = map(lambda p: QPoint(p[0], p[1]), points)
        self.painter.drawPolyline(QPolygon(points))

    def fillRect(self, x, y, width, height, r, g, b, a=255):
        self.painter.fillRect(QRect(x, y, width, height), QColor(r, g, b, a))
Beispiel #33
0
	def paintEvent(self, event):
		  
		painter = QPainter(self)
		painter.setPen(self.pen)
		painter.setBrush(self.brush)
		if self.antialiased:
			painter.setRenderHint(QPainter.Antialiasing)

		angle_step = 360 / self.n_states

		painter.save()	#Save_1. Save the state of the system (push matrix)
		painter.translate(self.dist_center.x(), self.dist_center.y())		# go to the center of the render area
		painter.rotate(-180)	#to start painting from the left side of the circle (clockwise)

		#center of the circumference where through we are going to paint our states 
		x = self.dist_radius * math.cos(0)	
		y = self.dist_radius * math.sin(0)


		for h in range(self.n_states):

			rot = angle_step * h 	# each state is equidistant from the others. We paint them in circles

			painter.save()			#Save_2
			painter.rotate(rot)		#now our system is pointing to the next state to be drawn
			painter.translate(x,y)	#now our origin is in the center of the next state to be drawn

			#if the state is active, fill it green
			if self.machine.getState(h).isActive():	
				painter.setBrush(self.greenGradientBrush)			
			painter.drawEllipse(QPoint(0,0), self.state_radius, self.state_radius)	#draw the new state

			#global position of transformed coordinates (before any transformation, origin at top-left corner)
			gx = painter.worldTransform().map(QPoint(0,0)).x()
			gy = painter.worldTransform().map(QPoint(0,0)).y()
			self.machine.getState(h).setPos(gx, gy)		#store the center of the state without any transformation applied

			# text transformation. Our origin is still in the center of the current state
			painter.save()			#Save_3
			painter.rotate(180)		#making the text go vertical
			painter.rotate(-rot)	#undoing the rotation made for painting the state. No the text is horizontal
			font = painter.font();
			font.setPixelSize(self.state_radius*.4);
			painter.setFont(font);
			rect = QRect(-self.state_radius, -self.state_radius, self.state_radius*2, self.state_radius*2)
			painter.drawText(rect, Qt.AlignCenter, self.machine.getState(h).getName());
			painter.restore()	#Restore_3
			#end text transformation

			painter.restore()	#Restore_2
			
		painter.restore()	#Restore_1. Restore the state of the system (pop matrix)

		
		#drawing transitions. Line between states
		painter.save()	# Save_4
		pptv = QTransform()		#Define a new transformation. Needed to rotate the system along other axis than Z
		pptv.translate(0, self.height())	#We are now at the bottom-left corner of the screen
		pptv.rotate(-180, Qt.XAxis)			#Rotate along the X-axis so now we are in a typical cartesian system.
		painter.setTransform(pptv)			#Apply the transformation
		states = self.machine.getStates()
		for state in states:
			transitions = state.getTransitions()
			for transition in transitions:
				#get the center of the origin and destination states in our current system state
				orig = QPoint(state.getPos()[0], state.getPos()[1])
				end = QPoint(self.machine.getState(transition.getStateEnd()).getPos()[0], self.machine.getState(transition.getStateEnd()).getPos()[1])
				# get those coordinates without transformation
				orig2 = QPoint(painter.worldTransform().map(orig))
				end2 = QPoint(painter.worldTransform().map(end))

				#get the angle between states centers and the horizon
				angle = math.atan2(end2.y() - orig2.y(), end2.x() - orig2.x())

				#get the coordinates of the starting point of the transition (it starts in the bound of the state, not in the center)
				newX = self.state_radius * math.cos(angle) + orig2.x()
				newY = self.state_radius * math.sin(angle) + orig2.y()
				#now the transition starts at the border, not in the center
				orig2.setX(newX)
				orig2.setY(newY)

				#same for the destination state
				angle2 = math.atan2(orig2.y() - end2.y(), orig2.x() - end2.x())
				newX2 = self.state_radius * math.cos(angle2) + end2.x()
				newY2 = self.state_radius * math.sin(angle2) + end2.y()
				end2.setX(newX2)
				end2.setY(newY2)

				#draw the line between the origin and destination states
				painter.drawLine(orig2, end2)
				#get the start and the end of the transition untransformed
				init = QPoint(painter.worldTransform().map(orig2))
				end = QPoint(painter.worldTransform().map(end2))
				#store that info
				transition.setOrig(init.x(), init.y())
				transition.setDest(end.x(), end.y())	
				transition.setAngle(angle)
		painter.restore() #Restore_4


		#Appliying style to the transitions
		painter.setPen(QPen(QColor(Qt.gray), 3))
		for state in self.machine.getStates():
			for transition in state.getTransitions():
				#get the start and end coordinates of the transition
				i = QPoint(transition.getOrig()[0], transition.getOrig()[1])
				o = QPoint(transition.getDest()[0], transition.getDest()[1])			
				painter.drawPolyline(i, o)

				#Drawing the arrow at the end of the transition
				painter.save()	#Save_5
				painter.setPen(QPen(QColor(Qt.gray), 2))
				painter.translate(transition.getDest()[0],transition.getDest()[1])	#Go to the end of the transition
				painter.rotate(90 - transition.getAngle()*180/math.pi)		#Rotate to point in the direction of the transition

				#coordinates of the arrow (triangle)
				a = QPoint(0,0)
				b = QPoint(-5,10)
				c = QPoint(5,10)

				#coordinates of the arrow untransformed
				a1 = painter.worldTransform().map(a)
				b1 = painter.worldTransform().map(b)
				c1 = painter.worldTransform().map(c)

				#Drawin the actual arrow
				pointer = QPolygon([a,b,c])
				painter.drawPolygon(pointer)
				painter.restore()	#Restore_5

				#For the animation of the transition
				painter.save()	#Save_6
				if transition.isActive():	#if the current transition is the active one the wave function will be running, so it's updating the canvas

					painter.setPen(QPen(QColor(Qt.green), 3))
					painter.drawPolyline(i,o)
					
					painter.setPen(QPen(QColor(Qt.gray), 3))
					painter.drawPolyline(self.poly(self.pts))

					#Draw the arrow in the active state (red arrow)
					painter.setBrush(QBrush(QColor(255, 0, 0)))
					painter.setPen(QPen(QColor(Qt.red), 2))
					pointer = QPolygon([a1,b1,c1])
					painter.drawPolygon(pointer)
					
					#Ball that follows the line animation
					for x, y in self.pts:
						painter.drawEllipse(QRectF(self.pts[0][0] - 4, self.pts[0][1] - 4, 8, 8))
				painter.restore()	#Restore_6

				#Painting the text of the transition
				painter.save()	#Save_7
				pptv = QTransform()
				painter.setPen(QPen(QColor(Qt.black), 3))
				#get the middle point of the transition
				middleX = (transition.getOrig()[0] + transition.getDest()[0]) /2	
				middleY = (transition.getOrig()[1] + transition.getDest()[1]) /2
				pptv.translate(middleX, middleY)	#translate to that point
				painter.setTransform(pptv)			#apply the transformation
				font = painter.font();
				font.setPixelSize(self.state_radius*.2);
				painter.setFont(font);
				rect = QRect(-self.state_radius, -self.state_radius, self.state_radius*2, self.state_radius*2)
				name = str(transition.getId())+ '. ' + transition.getName()
				painter.drawText(rect, Qt.AlignCenter, name)
				painter.restore()	#Restore_7


  
		#paint the actual canvas
		painter.setPen(self.palette().dark().color())
		painter.setBrush(Qt.NoBrush)
		painter.drawRect(QRect(0, 0, self.width() - 1, self.height() - 1))
Beispiel #34
0
    def paintEvent(self, event):  # 在窗口上绘图
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setRenderHint(QPainter.TextAntialiasing)
        ##设置画笔
        pen = QPen()
        pen.setWidth(3)
        pen.setColor(Qt.black)
        pen.setStyle(Qt.SolidLine)
        pen.setCapStyle(Qt.FlatCap)
        pen.setJoinStyle(Qt.BevelJoin)
        painter.setPen(pen)
        ##设置画刷
        brush = QBrush()
        brush.setColor(Qt.yellow)
        brush.setStyle(Qt.SolidPattern)
        painter.setBrush(brush)

        ##绘制货架
        W = self.width()
        H = self.height()
        rect1 = QRect(0, H*4/ 18, W*3 / 24, H*3 / 17)
        rect2 = QRect(0, H * 12 / 18, W*3 / 24, H *3/ 17)
        painter.drawRects(rect1,rect2)

        font = painter.font()
        font.setPointSize(0.0225*W)
        font.setBold(True)
        painter.setFont(font)
        rect = QRect(0, 0, W, H / 8)
        painter.drawText(rect, Qt.AlignCenter, '仓库平面图')
        painter.drawText(rect1,Qt.AlignCenter,'出口')
        painter.drawText(rect2, Qt.AlignCenter, '入口')
        shelfName=[['A1','A2','A3'],['B1','B2','B3'],
                   ['C1','C2','C3'],['D1','D2','D3']]

        horGap, horWidth, horDistance = 2, 4, 2
        verGap, verWidth, verDistance = 1, 2, 3
        horlen = 4 * horGap + 3 * horWidth + 2 * horDistance  #24
        verlen = 3 * verGap + 4 * verWidth + 3 * verDistance-2  #17

        for i in range(4):
            for j in range(3):
                if i==2:
                    ver=3-2/2
                elif i==3:
                    ver=3-2/3
                else:
                    ver = verDistance
                rect = QRect(W * (3*horGap + j * (horWidth + horDistance)) / horlen,
                             H * (2*verGap + i * (verWidth + ver)) / verlen,
                             W * (horWidth) / horlen, H * (verWidth) / verlen)
                painter.drawRect(rect)
                painter.drawText(rect, Qt.AlignCenter, shelfName[i][j])
        colorsix=[QColor(255,181,73),QColor(65,182,230),QColor(254,95,85),
                  QColor(30,227,207),QColor(13,63,103),QColor(228,23,73)]
        if self.allPoint!=[]:
            for i in range(len(self.allPoint)):
                points = []
                pen.setColor(colorsix[i])
                painter.setPen(pen)
                for point in self.allPoint[i]:
                    points.append(QPoint(point[0]*W/horlen-6*i,point[1]*H/verlen+6*i))
                painter.drawPolyline(QPolygon(points))
	def updateROIcanvas(self, wormCanvas, worm_index_roi, comboBox_ROI, isDrawSkel):
		if not isinstance(self.frame_data, pd.DataFrame):
			wormCanvas.clear()
			return
		
		#update valid index for the comboBox
		comboBox_ROI.clear()
		comboBox_ROI.addItem(str(worm_index_roi))
		
		for ind in self.frame_data[self.worm_index_str].data:
			comboBox_ROI.addItem(str(ind))
		
		
		#extract individual worm ROI
		good = self.frame_data[self.worm_index_str] == worm_index_roi
		roi_data = self.frame_data.loc[good].squeeze()

		if roi_data.size == 0:
			wormCanvas.clear()
			return

		if np.isnan(roi_data['coord_x']) or np.isnan(roi_data['coord_y']):
			return #invalid coordinate, nothing to do here

		worm_roi, roi_corner = getWormROI(self.original_image, roi_data['coord_x'], roi_data['coord_y'], roi_data['roi_size'])
		roi_corner = roi_corner+1
		#worm_roi, roi_corner = self.original_image, np.zeros(2)

		roi_ori_size = worm_roi.shape
		
		worm_roi = np.ascontiguousarray(worm_roi)
		#worm_roi = cv2.cvtColor(worm_img, cv2.COLOR_GRAY2RGB);

		worm_img = QImage(worm_roi.data, worm_roi.shape[1], worm_roi.shape[0], worm_roi.strides[0], QImage.Format_Indexed8)
		worm_img = worm_img.convertToFormat(QImage.Format_RGB32, Qt.AutoColor)

		
		canvas_size = min(wormCanvas.height(),wormCanvas.width())
		worm_img = worm_img.scaled(canvas_size,canvas_size, Qt.KeepAspectRatio)#, Qt.SmoothTransformation)
		
		
		if isDrawSkel:
			if roi_data['has_skeleton']==1:
				c_ratio_y = worm_img.width()/roi_ori_size[1];
				c_ratio_x = worm_img.height()/roi_ori_size[0];
				
				skel_id = int(roi_data['skeleton_id'])

				qPlg = {}
				
				for tt in ['skeleton', 'contour_side1', 'contour_side2']:
					dat = self.skel_dat[tt][skel_id];
					dat[:,0] = (dat[:,0]-roi_corner[0])*c_ratio_x
					dat[:,1] = (dat[:,1]-roi_corner[1])*c_ratio_y
					
					#dat = (self.skel_dat[tt][skel_id] - 0)*c_ratio
					qPlg[tt] = QPolygonF()
					for p in dat:
						qPlg[tt].append(QPointF(*p))
				
				if 'is_good_skel' in roi_data and roi_data['is_good_skel'] == 0:
					self.skel_colors = {'skeleton':(102, 0, 0 ), 
					'contour_side1':(102, 0, 0 ), 'contour_side2':(102, 0, 0 )}
				else:
					self.skel_colors = {'skeleton':(27, 158, 119 ), 
					'contour_side1':(217, 95, 2), 'contour_side2':(231, 41, 138)}

				pen = QPen()
				pen.setWidth(2)
				
				painter = QPainter()
				painter.begin(worm_img)
			
				for tt, color in self.skel_colors.items():
					pen.setColor(QColor(*color))
					painter.setPen(pen)
					painter.drawPolyline(qPlg[tt])
				
				pen.setColor(Qt.black)
				painter.setBrush(Qt.white)
				painter.setPen(pen)
			
				radius = 3#*c_ratio_x
				painter.drawEllipse(qPlg['skeleton'][0], radius, radius)

				painter.end()
			elif roi_data['has_skeleton']==0:
				worm_mask = getWormMask(worm_roi, roi_data['threshold'])
				worm_cnt, _ = binaryMask2Contour(worm_mask)
				worm_mask = np.zeros_like(worm_mask)
				cv2.drawContours(worm_mask, [worm_cnt.astype(np.int32)], 0, 1, -1)

				worm_mask = QImage(worm_mask.data, worm_mask.shape[1], 
					worm_mask.shape[0], worm_mask.strides[0], QImage.Format_Indexed8)
				worm_mask = worm_mask.convertToFormat(QImage.Format_RGB32, Qt.AutoColor)
				worm_mask = worm_mask.scaled(canvas_size,canvas_size, 
					Qt.KeepAspectRatio)#, Qt.SmoothTransformation)
				worm_mask = QPixmap.fromImage(worm_mask)

				worm_mask = worm_mask.createMaskFromColor(Qt.black)
				p = QPainter(worm_img)
				p.setPen(QColor(0,204,102))
				p.drawPixmap(worm_img.rect(), worm_mask, worm_mask.rect())
				p.end()

		
		pixmap = QPixmap.fromImage(worm_img)
		wormCanvas.setPixmap(pixmap);
Beispiel #36
0
    def paintEvent(self, event=None):
        LogicalSize = 100.0

        def logicalFromPhysical(length, side):
            return (length / side) * LogicalSize

        fm = QFontMetricsF(self.font())
        ymargin = (
            (LogicalSize / 30.0) +
            logicalFromPhysical(self.leftSpinBox.height(), self.height()))
        ymax = (LogicalSize -
                logicalFromPhysical(fm.height() * 2, self.height()))
        width = LogicalSize / 4.0
        cx, cy = LogicalSize / 2.0, LogicalSize / 3.0
        ax, ay = cx - (2 * width), ymargin
        bx, by = cx - width, ay
        dx, dy = cx + width, ay
        ex, ey = cx + (2 * width), ymargin
        fx, fy = cx + (width / 2), cx + (LogicalSize / 24.0)
        gx, gy = fx, ymax
        hx, hy = cx - (width / 2), ymax
        ix, iy = hx, fy

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        side = min(self.width(), self.height())
        painter.setViewport((self.width() - side) / 2,
                            (self.height() - side) / 2, side, side)
        painter.setWindow(0, 0, LogicalSize, LogicalSize)

        painter.setPen(Qt.NoPen)

        gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 100))
        gradient.setColorAt(0, Qt.white)
        a = self.leftSpinBox.value()
        gradient.setColorAt(1, (Qt.red if a != 0 else Qt.white))
        painter.setBrush(QBrush(gradient))
        painter.drawPolygon(
            QPolygonF([
                QPointF(ax, ay),
                QPointF(bx, by),
                QPointF(cx, cy),
                QPointF(ix, iy)
            ]))

        gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 100))
        gradient.setColorAt(0, Qt.white)
        b = self.rightSpinBox.value()
        gradient.setColorAt(1, (Qt.blue if b != 0 else Qt.white))
        painter.setBrush(QBrush(gradient))
        painter.drawPolygon(
            QPolygonF([
                QPointF(cx, cy),
                QPointF(dx, dy),
                QPointF(ex, ey),
                QPointF(fx, fy)
            ]))

        if (a + b) == 0:
            color = QColor(Qt.white)
        else:
            ashare = (a / (a + b)) * 255.0
            bshare = 255.0 - ashare
            color = QColor(ashare, 0, bshare)
        gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 100))
        gradient.setColorAt(0, Qt.white)
        gradient.setColorAt(1, color)
        painter.setBrush(QBrush(gradient))
        painter.drawPolygon(
            QPolygonF([
                QPointF(cx, cy),
                QPointF(fx, fy),
                QPointF(gx, gy),
                QPointF(hx, hy),
                QPointF(ix, iy)
            ]))

        painter.setPen(Qt.black)
        painter.drawPolyline(
            QPolygonF([QPointF(ax, ay),
                       QPointF(ix, iy),
                       QPointF(hx, hy)]))
        painter.drawPolyline(
            QPolygonF([QPointF(gx, gy),
                       QPointF(fx, fy),
                       QPointF(ex, ey)]))
        painter.drawPolyline(
            QPolygonF([QPointF(bx, by),
                       QPointF(cx, cy),
                       QPointF(dx, dy)]))