PolyLineROI drawing polygons in pyqtgraph is slow when the number of points is large

44 Views Asked by At

I want to display polygons through pyqtgraph, if drawn with Pyqtgraph.polygonroi, dot by mouse, but when the number of points is too many program cards, how to solve

package:

import cv2
import numpy as np
import pyqtgraph as pg
from PyQt5.QtCore import QPoint, QPointF, Qt
from PyQt5.QtWidgets import QApplication, QAction
import tifffile

from datashader import Point
from pyqtgraph import functions as fn



class ImageViewBox(pg.ViewBox):
    def __init__(self, file_path, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.file_path=file_path
        self.draw=False
        self.polygons = []  
        self.setMenuEnabled(True) 
        if self.file_path.endswith(".tif"):
            self.image_data = tifffile.imread(self.file_path)
        else:
            self.image_data = cv2.imread(self.file_path, cv2.IMREAD_UNCHANGED)
        self.image_data = self.image_data.astype(np.uint16) 


        pyramid_levels = 3  
        for _ in range(pyramid_levels):
            self.image_data = cv2.pyrDown(self.image_data)


        self.imageitem = pg.ImageItem(self.image_data)
        self.addItem(self.imageitem)


    def mouse_click(self, ev):
        if ev.button()==Qt.LeftButton:
        
            pos_scene = ev.scenePos()
            start_pos = self.mapSceneToView(pos_scene)
            if not self.imageitem.sceneBoundingRect().contains(pos_scene):
                return

            if not self.draw:
               
                polygon = pg.PolyLineROI(positions=[],closed=True, pen='g', movable=False)

                self.polygons.append(polygon)
               
                self.addItem(self.polygons[-1])
                self.draw = True

            if len(self.polygons[-1].getSceneHandlePositions()) > 2:
                last_poygon = self.polygons[-1].saveState()['points'][-1]
                last_point = np.array([last_poygon[0], last_poygon[1]])
                pos_array = np.array([ev.pos().x(), ev.pos().y()])
                distance = np.linalg.norm(pos_array - last_point)
                if distance < 50:
                    self.draw = False
                    return

            self.add_point(start_pos)


        if ev.button() == Qt.MiddleButton:
            if self.draw == True:
                self.draw = False

            elif self.draw == False and len(self.polygons[-1].saveState()['points'] )> 0:
                print(len(self.polygons[-1].saveState()['points'] ))
                self.draw =True

    def add_point(self,point):
        
        current_polygon_points = self.polygons[-1].saveState()['points']


        current_polygon_points.append(point)
        self.polygons[-1].setPoints(current_polygon_points)

enter image description here

Like this, the number of ticks is high, the program is very slow

0

There are 0 best solutions below