def display_points(self): self.clear_points() if self.current_image_name in self.points: display_radius = self.ui['point']['radius'] active_color = QtGui.QColor(self.ui['point']['color'][0], self.ui['point']['color'][1], self.ui['point']['color'][2]) active_brush = QtGui.QBrush(active_color, QtCore.Qt.BrushStyle.SolidPattern) active_pen = QtGui.QPen(active_brush, 2) for class_name in self.points[self.current_image_name]: points = self.points[self.current_image_name][class_name] brush = QtGui.QBrush(self.colors[class_name], QtCore.Qt.BrushStyle.SolidPattern) pen = QtGui.QPen(brush, 2) for point in points: if class_name == self.current_class_name: self.addEllipse( QtCore.QRectF( point.x() - ((display_radius - 1) / 2), point.y() - ((display_radius - 1) / 2), display_radius, display_radius), active_pen, active_brush) else: self.addEllipse( QtCore.QRectF( point.x() - ((display_radius - 1) / 2), point.y() - ((display_radius - 1) / 2), display_radius, display_radius), pen, brush)
def __init__(self): QtWidgets.QGraphicsScene.__init__(self) self.points = {} self.colors = {} self.coordinates = {} self.custom_fields = {'fields': [], 'data': {}} self.classes = [] self.selection = [] self.ui = { 'grid': { 'size': 200, 'color': [255, 255, 255] }, 'point': { 'radius': 25, 'color': [255, 255, 0] } } self.directory = '' self.current_image_name = None self.current_class_name = None self.qt_image = None self.show_grid = True self.selected_pen = QtGui.QPen( QtGui.QBrush(QtCore.Qt.GlobalColor.red, QtCore.Qt.BrushStyle.SolidPattern), 1)
def undo(self): if self.iw.measuring_length: self.iw._thispos = self.iw._lastpos self.iw.L.downdate() #remove data self.iw.line_count += -1 self.iw.scene.removeItem(self.iw.scene.realline) #remove graphic self.iw.scene.realline = False if self.iw.measuring_area: self.iw._thispos = self.iw._lastpos self.iw.A.downdate() #remove data self.iw.line_count += -1 self.iw.scene.removeItem(self.iw.scene.realline) #remove graphic self.iw.scene.realline = False if self.iw.measuring_widths: self.iw.W.downdate() #remove data self.iw.scene.removeItem(self.iw.scene.ellipseItem) #remove graphic self.iw.scene.ellipseItem = False self.iw.d[str(self.iw.k)].setPen( QtGui.QPen(QtGui.QColor('black'))) #un-highlight next spine self.iw.k += -1 #reduce count if self.iw.measuring_angle: self.iw.T.downdate() #remove data self.iw._thispos = self.iw_lastpos self.iw.scene.removeItem(self.iw.scene.realline) #remove graphic self.iw.scene.realline = False
def addCanvasLine(self, p1, p2, color=(0, 0, 0), color2=None, **kwargs): if 'dash' in kwargs: line_type = PenStile_DashLine else: line_type = PenStile_SolidLine qp1 = QtCore.QPointF(*p1) qp2 = QtCore.QPointF(*p2) qpm = QtCore.QPointF((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2) if color2 and color2 != color: rgb = [int(c * 255) for c in color] pen = QtGui.QPen(QtGui.QColor(*rgb), 1, line_type) self.painter.setPen(pen) self.painter.drawLine(qp1, qpm) rgb2 = [int(c * 255) for c in color2] pen.setColor(QtGui.QColor(*rgb2)) self.painter.setPen(pen) self.painter.drawLine(qpm, qp2) else: rgb = [int(c * 255) for c in color] pen = QtGui.QPen(QtGui.QColor(*rgb), 1, line_type) self.painter.setPen(pen) self.painter.drawLine(qp1, qp2)
def addCanvasPolygon(self, ps, color=(0, 0, 0), fill=True, stroke=False, **kwargs): polygon = QtGui.QPolygonF() for ver in ps: polygon.append(QtCore.QPointF(*ver)) color = [int(c * 255) for c in color] pen = QtGui.QPen(QtGui.QColor(*color), 1, PenStile_DashLine) self.painter.setPen(pen) self.painter.setBrush(QtGui.QColor(0, 0, 0)) self.painter.drawPolygon(polygon)
def display_grid(self): self.clear_grid() if self.current_image_name and self.show_grid: grid_color = QtGui.QColor(self.ui['grid']['color'][0], self.ui['grid']['color'][1], self.ui['grid']['color'][2]) grid_size = self.ui['grid']['size'] rect = self.itemsBoundingRect() brush = QtGui.QBrush(grid_color, QtCore.Qt.BrushStyle.SolidPattern) pen = QtGui.QPen(brush, 1) for x in range(grid_size, int(rect.width()), grid_size): line = QtCore.QLineF(x, 0.0, x, rect.height()) self.addLine(line, pen) for y in range(grid_size, int(rect.height()), grid_size): line = QtCore.QLineF(0.0, y, rect.width(), y) self.addLine(line, pen)
def addCanvasDashedWedge(self, p1, p2, p3, dash=(2, 2), color=(0, 0, 0), color2=None, **kwargs): rgb = [int(c * 255) for c in color] pen = QtGui.QPen(QtGui.QColor(*rgb), 1, PenStile_DashLine) self.painter.setPen(pen) dash = (4, 4) pts1 = self._getLinePoints(p1, p2, dash) pts2 = self._getLinePoints(p1, p3, dash) if len(pts2) < len(pts1): pts2, pts1 = pts1, pts2 for i in range(len(pts1)): qp1 = QtCore.QPointF(pts1[i][0], pts1[i][1]) qp2 = QtCore.QPointF(pts2[i][0], pts2[i][1]) self.painter.drawLine(qp1, qp2)
def add_point(self, point): if self.current_image_name is not None and self.current_class_name is not None: if self.current_class_name not in self.points[ self.current_image_name]: self.points[self.current_image_name][ self.current_class_name] = [] display_radius = self.ui['point']['radius'] active_color = QtGui.QColor(self.ui['point']['color'][0], self.ui['point']['color'][1], self.ui['point']['color'][2]) active_brush = QtGui.QBrush(active_color, QtCore.Qt.BrushStyle.SolidPattern) active_pen = QtGui.QPen(active_brush, 2) self.points[self.current_image_name][ self.current_class_name].append(point) self.addEllipse( QtCore.QRectF(point.x() - ((display_radius - 1) / 2), point.y() - ((display_radius - 1) / 2), display_radius, display_radius), active_pen, active_brush) self.update_point_count.emit( self.current_image_name, self.current_class_name, len(self.points[self.current_image_name][ self.current_class_name]))
def mousePressEvent(self, event): #http://pyqt.sourceforge.net/Docs/PyQt4/qgraphicsscenemouseevent.html #https://stackoverflow.com/questions/21197658/how-to-get-pixel-on-qgraphicspixmapitem-on-a-qgraphicsview-from-a-mouse-click data = self.mapToScene(event.pos()) #draw piecewise lines for non-width measurements rules = [self.measuring_length, self.measuring_angle, self.measuring_area] if self.scene.testline and self._thispos and any(rules): start = self._thispos end = QtCore.QPointF(data) if self._lastpos and self.measuring_angle: a = self._lastpos - self._thispos b = data - self._thispos a = np.array([a.x(), a.y()]) b = np.array([b.x(), b.y()]) self.measuring_angle = False t = np.arccos(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))) t *= 180 / np.pi #convert to degrees self.T.update(t) self.angleValues = np.append(self.angleValues,t) self.parent().statusbar.showMessage('Angle measurement complete') self.parent().angleButton.setChecked(False) self.parent().bezier.setEnabled(True) self.scene.realline = QGraphicsLineItem(QtCore.QLineF(start, end)) self.scene.addItem(self.scene.realline) #Collect piecewise line start/end points self._lastpos = self._thispos # save old position value self._thispos = QtCore.QPointF(data) # update current position if self.measuring_length: self.L.update(data.x(), data.y()) # update total length self.line_count += 1 elif self.measuring_area: self.line_count += 1 intersect = False if self.line_count > 2: #cant make polygon w/ two lines intersect, xi, yi, k = self.A.checkIntersect(data.x(),data.y()) self.parent().areaButton.setEnabled(True) if intersect: self.measuring_area = False self.A.update(xi,yi) #update with intersect point self.A.x, self.A.y = self.A.x[k:], self.A.y[k:] #only use points after intersection A = self.A.calcArea() self.areaValues = np.append(self.areaValues, A) #add area values #draw permanent polygon points = [ QtCore.QPointF(x,y) for x,y in zip( self.A.x, self.A.y ) ] self.scene.polyItem2 = QGraphicsPolygonItem(QtGui.QPolygonF(points)) self.scene.polyItem2.setBrush( QtGui.QBrush(QtGui.QColor(255,255,255,127)) ) self.scene.removeItem(self.scene.polyItem) #remove mouseover polygon self.scene.polyItem = False #remove mouseover polygon self.scene.addItem(self.scene.polyItem2) #shade in polygon self.parent().statusbar.showMessage('Polygon area measurement completed') self.parent().areaButton.setChecked(False) self.parent().bezier.setEnabled(True) #make bezier fit available again QApplication.setOverrideCursor(QtCore.Qt.ArrowCursor) #change cursor else: self.A.update(data.x(),data.y()) #update with click point #https://stackoverflow.com/questions/30898846/qgraphicsview-items-not-being-placed-where-they-should-be if self.measuring_widths: #measure widths, snap to spines k = int(self.k / 2) + 1 #same origin for spine on either side x0, y0 = self.xp[k], self.yp[k] x1, y1 = data.x(), data.y() #perpindicular slopes vx = self.slopes[:,k][1] vy = -self.slopes[:,k][0] A = np.matrix([[vx, -vy], [vy, vx]]) b = np.array([x1 - x0, y1 - y0]) t = np.linalg.solve(A,b) xi = x0 + t[0]*vx yi = y0 + t[0]*vy self.W.update(xi,yi) p = QtCore.QPointF(xi, yi) s = 10 #dot size self.scene.ellipseItem = QGraphicsEllipseItem(0, 0, s, s) self.scene.ellipseItem.setPos(p.x() - s / 2, p.y() - s / 2) qb = QtGui.QBrush() qb.setColor(QtGui.QColor('red')) self.scene.ellipseItem.setBrush(qb) self.scene.ellipseItem.setFlag( QGraphicsItem.GraphicsItemFlag.ItemIgnoresTransformations, False) #size stays small, but doesnt translate if false self.scene.addItem(self.scene.ellipseItem) self.k += 1 if self.k < self.nspines: self.d[str(self.k)].setPen(QtGui.QPen( QtGui.QColor('yellow'))) #Highlight next spine if self.k == self.nspines: self.parent().statusbar.showMessage('Width measurements complete') self.measuring_widths = False self.parent().widthsButton.setEnabled(False) self.parent().widthsButton.setChecked(False) self.parent().bezier.setEnabled(True) width = np.sqrt( (self.W.x[1::2] - self.W.x[0::2])**2 + (self.W.y[1::2] - self.W.y[0::2])**2) #calculate widths self.widths[-1] = width
def measure_widths(self): def qpt2pt(x, y): Q = self.mapFromScene( self.mapToScene( int(x), int(y)) ) return Q.x(), Q.y() self.measuring_widths = True self.parent().widthsButton.setChecked(True) self.k = 0 self.W = posData( np.empty(shape=(0, 0)), np.empty(shape=(0, 0))) #preallocate custom widths #number of possible measurements per segment (length + #widths) #self.measurements = np.empty((0, self.iw.nm + 1), int) * np.nan self.numwidths = int(self.parent().subWin.numwidths.text()) #self.measurements[-1] = np.append( self.l[-1], np.zeros(self.numwidths-1)*np.nan ) #preallocate measurements self.widths[-1] = np.empty(self.numwidths-1, dtype='float') #preallocate measurements self.widthNames[-1] = [ '{0:2.2f}% Width'.format(100 * f / self.numwidths) for f in np.arange(1, self.numwidths) ] self.nspines = 2 * (self.numwidths - 1) self.parent().statusbar.showMessage( 'Click point along spines to make width measurements perpindicular to the length segment' ) #get pts for width drawing bins = np.linspace(0, self.l[-1], self.numwidths + 1) inds = np.digitize(self.l, bins) __, self.inddec = np.unique(inds, return_index = True) pts = np.array(list(map(qpt2pt, self.xs, self.ys))) x, y = pts[:, 0], pts[:, 1] self.xp, self.yp = x[self.inddec], y[self.inddec] self.slopes = self.m[:,self.inddec] #Identify width spine points self.xsw = x[inds] self.ysw = y[inds] #Draw Widths for k,(x,y) in enumerate(zip(self.xp[1:-1], self.yp[1:-1])): x1, y1 = x,y L = self.pixmap_fit.width() H = self.pixmap_fit.height() v = self.slopes[:,k+1] vx = v[1] vy = -v[0] t0 = np.hypot(L,H) t2 = 0 #intersect: rectangle for offset in ([0,0],[L,H]): for ev in ([1,0],[0,1]): A = np.matrix([ [vx, ev[0]] , [vy, ev[1]] ]) b = np.array([offset[0] - x1, offset[1] - y1]) T = np.linalg.solve(A,b)[0] t0 = min(T, t0, key=abs) #find nearest intersection to bounds #Find 2nd furthest intersection within bounds bounds = np.array( [(L - x1)/vx, (H - y1)/vy, -x1/vx, -y1/vy] ) t2 = max(-t0, np.sign(-t0)* np.partition(bounds,-2)[-2], key=abs) x0 = x1 + t0*vx y0 = y1 + t0*vy x2 = x1 + t2*vx y2 = y1 + t2*vy for l, (x, y) in enumerate(zip([x0, x2], [y0, y2])): start = QtCore.QPointF(x1, y1) end = QtCore.QPointF(x, y) self.scene.interpLine = QGraphicsLineItem( QtCore.QLineF(start, end)) self.d["{}".format(2 * k + l)] = self.scene.interpLine self.scene.addItem(self.scene.interpLine) if k == 0 and l == 0: self.scene.interpLine.setPen( QtGui.QPen(QtGui.QColor('yellow')))