Python交互式选择工具,类似于MATLAB

5
我正在尝试从MATLAB转换到Python,但现在我遇到了一些问题,无法自行解决。我使用Qt Designer(用于分析某些神经元)在pyqt中设计了GUI,所有可视化都是在matplotlib widget for Qt中完成的(它包含在pythonxy中),但现在我需要一些像MATLAB中一样的工具,用于与集成在Qt GUI中的matplotlib进行交互式选择(不仅限于图像,还包括绘图):

  • imline
  • impoly
  • imellipse
  • imfreehand
  • imrect(在pyqt GUI中不起作用imrect for python);
  • ginput(我可以直接调用ginput on myMatplotlibWidget.figure.ginput(),在matplotlib\blocking_input.py文件中注释了self.fig.show()命令后,这个命令来自matplotlib库)。

我发现了这个http://matplotlib.org/users/event_handling.html,请不要告诉我我必须使用这个python模块自己实现上述工具xD

我发现了这个http://www.pyqtgraph.org/,但它没有与matplotlib集成,最终呈现的效果也不如matplotlib好。

有没有适用于pyqt的良好交互式选择工具?在Google上,我找不到任何有用的东西,但我无法相信Python没有好的交互式工具...如果是这样,我将回到MATLAB。

感谢任何帮助


2
考虑到您正在使用Qt来制作GUI,请使用Qt的工具构建所需内容(例如QRubberBand等)。虽然对于matplotlib也有类似的工具,但如果您将其嵌入到Qt中,则没有必要使用与GUI无关的matplotlib小部件。 - Joe Kington
我是Qt和Python的新手,我只是因为它非常接近MATLAB绘图、直方图、stem、imshow工具,所以在Qt中使用matplotlib小部件。无论如何,我将尝试自己编写我需要的交互式工具在pyqt :) QRubberBand类对我来说似乎是一个很好的起点;你有关于Qt类实现一些交互式工具(主要是绘制线条、矩形、多边形等)的其他建议吗? - opensw
3个回答

4

好的,我已经为在Qt GUI中集成matplotlib自行实现了imline...现在,实现imrect等内容也很简单。如果有人需要imrect等内容,我将更新代码。以下是我实现imline的代码:

from PyQt4.QtCore import *
from PyQt4.QtGui import *

import time
import matplotlib as mpl
import matplotlib.pyplot as plt

import numpy as np
import scipy.optimize as opt


class Imline(QObject):
    '''
    Plot interactive line
    '''

    def __init__(self, plt, image = None, scale = 1, *args, **kwargs):
        '''
        Initialize imline
        '''
        super(Imline, self).__init__(None)

        # set plot        
        self.__plt = plt
        self.scale = scale        

        # initialize start and end points        
        self.startX = None
        self.startY = None
        self.endX = None
        self.endY = None  

        # initialize line2d        
        self.__line2d = None
        self.mask = None

        # store information to generate mask
        if(image is not None):        
            height, width = image.shape

        else:
            height = None
            width = None            

        self.__width = width
        self.__height = height

        # set signals and slots        
        self.__c1 = self.__plt.figure.canvas.mpl_connect('button_press_event', self.__mousePressEvent)
        self.__c2 = self.__plt.figure.canvas.mpl_connect('motion_notify_event', self.__mouseMoveEvent)
        self.__c3 = self.__plt.figure.canvas.mpl_connect('button_release_event', self.__mouseReleaseEvent)       

        self.imlineEventFinished = SIGNAL('imlineEventFinished')        


    def __mousePressEvent(self, event):
        '''
        Starting point
        '''

        # get xy data        
        xdata = event.xdata
        ydata = event.ydata

        # check if mouse is outside the figure        
        if((xdata is None) | (ydata is None) | (self.startX is not None) | (self.startY is not None) | (self.endX is not None) | (self.endY is not None)):
            return       

        # start point        
        self.startX = xdata
        self.startY = ydata


    def __mouseMoveEvent(self, event):
        '''
        Draw interactive line
        '''

        # get xy data        
        xdata = event.xdata
        ydata = event.ydata

        # check if mouse is outside the figure        
        if((xdata is None) | (ydata is None) | (self.startX is None) | (self.startY is None) | (self.endX is not None) | (self.endY is not None)):
            return      

        # remove line        
        if(self.__line2d is not None):
            self.__line2d[0].remove()

        # set x, t
        x = [self.startX, xdata]
        y = [self.startY, ydata]        

        # plot line
        self.__plt.axes.hold(True)
        xlim = self.__plt.axes.get_xlim()
        ylim = self.__plt.axes.get_ylim()
        self.__line2d = self.__plt.axes.plot(x, y, color = [1, 0, 0])
        self.__plt.axes.set_xlim(xlim)
        self.__plt.axes.set_ylim(ylim)

        # update plot        
        self.__plt.draw()
        self.__plt.show()


    def __mouseReleaseEvent(self, event):
        '''
        End point
        '''     

        # get xy data        
        xdata = event.xdata
        ydata = event.ydata

        # check if mouse is outside the figure        
        if((xdata is None) | (ydata is None) | (self.endX is not None) | (self.endY is not None)):
            return             

        # remove line        
        if(self.__line2d is not None):
            self.__line2d[0].remove()

        self.endX = xdata
        self.endY = ydata   

        P = np.polyfit([self.startX, self.endX], [self.startY, self.endY],1 )
        self.__m = P[0]
        self.__q = P[1]

        # update plot        
        self.__plt.draw()
        self.__plt.show()

        # disconnect the vents        
        self.__plt.figure.canvas.mpl_disconnect(self.__c1)
        self.__plt.figure.canvas.mpl_disconnect(self.__c2)
        self.__plt.figure.canvas.mpl_disconnect(self.__c3)

        # emit SIGNAL        
        self.emit(SIGNAL('imlineEventFinished'))


    def createMask(self):
        '''
        Create mask from painted line
        '''

        # check height width        
        if((self.__height is None) | (self.__width is None)):
            return None

        # initialize mask        
        mask = np.zeros((self.__height, self.__width))        

        # get m q        
        m = self.__m
        q = self.__q        

        print m, q

        # get points        
        startX = np.int(self.startX)   
        startY = np.int(self.startY) 
        endX = np.int(self.endX) 
        endY = np.int(self.endY)

        # ensure startX < endX
        tempStartX = startX
        if(startX > endX):
            startX = endX
            endX = tempStartX

        # ensure startY < endY
        tempStartY = startY
        if(startY > endY):
            startY = endY
            endY = tempStartY

        # save points
        self.startX = startX
        self.endX = endX
        self.startY = startY
        self.endY = endY

        # intialize data        
        xData = np.arange(startX, endX)
        yData = np.arange(startY, endY)

        # scan on x        
        for x in xData:
            row = round(m*x + q)
            if(row < startY):
                row = startY
            if(row > endY):
                row = endY
            mask[row, x] = 1

        # scan on y
        for y in yData:
            col = round((y - q) / m)
            if(col < startX):
                col = startX
            if(col > endX):
                col = endX
            mask[y, col] = 1

        # get boolean mask        
        mask = mask == 1        

        # return boolean mask
        return mask

1
我认为这是在互联网上实现Python中imline类似行为的最佳资源。您能否再详细说明一下如何使用它(提供一个最小工作示例)? - Ralph

0

0

Matplotlib文档有一个简单的实现,可以在PyQt5中使用(为了方便起见,从那里复制整个示例)

from matplotlib import pyplot as plt

class LineBuilder:
    def __init__(self, line):
        self.line = line
        self.xs = list(line.get_xdata())
        self.ys = list(line.get_ydata())
        self.cid = line.figure.canvas.mpl_connect('button_press_event', self)

    def __call__(self, event):
        print('click', event)
        if event.inaxes!=self.line.axes: return
        self.xs.append(event.xdata)
        self.ys.append(event.ydata)
        self.line.set_data(self.xs, self.ys)
        self.line.figure.canvas.draw()

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('click to build line segments')
line, = ax.plot([0], [0])  # empty line
linebuilder = LineBuilder(line)

plt.show()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接