使用PyQt和matplotlib RectangleSelector裁剪图像

时间:2015-08-20 10:37:15

标签: python matplotlib pyqt4

我目前正在使用matplotlib和PyQT设计一个应用程序。 UI包含几个按钮和matplotlib小部件。

通过使用uic函数将UI设计动态链接 link

一键功能是以交互方式裁剪图像。我曾尝试使用matplotlib的RectangleSelector,但它不起作用。我也试过this例子。

我的代码:

import sys
from PyQt4 import QtCore, QtGui, uic
from os.path import expanduser
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from matplotlib.backends import qt4_compat
from matplotlib.figure import Figure
from matplotlib.widgets import RectangleSelector

form_class = uic.loadUiType("MTF_color_test.ui")[0]

class Ui_MainWindow(QtGui.QMainWindow, form_class):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.setupUi(self)
        self.pushButtonLoad.clicked.connect(self.LoadImage)
        self.pushButtonCrop.clicked.connect(self.CropImage)
        self.actionLoad.triggered.connect(self.LoadImage)

    def LoadImage(self):
        Path = str(QtGui.QFileDialog.getOpenFileName(None,
                                                          "Open an image",
                                                          expanduser("~"),
                                                           "Images (*.jpg *.png)"))
        if Path != '' and (Path.endswith(".jpg") or Path.endswith(".png")):
            print("Image file loaded")
            image = mpimg.imread(Path)
            self.widgetImage.canvas.ax.clear()
            self.widgetImage.canvas.ax.imshow(image)
            self.widgetImage.canvas.draw()

    def onselect(self, eclick, erelease):
        if eclick.ydata>erelease.ydata:
            eclick.ydata,erelease.ydata=erelease.ydata,eclick.ydata
        if eclick.xdata>erelease.xdata:
            eclick.xdata,erelease.xdata=erelease.xdata,eclick.xdata
        ax.set_ylim(erelease.ydata,eclick.ydata)
        ax.set_xlim(eclick.xdata,erelease.xdata)
        self.canvas.draw()
        print ' startposition : (%f, %f)' % (eclick.xdata, eclick.ydata)
        print ' endposition   : (%f, %f)' % (erelease.xdata, erelease.ydata)
        print ' used button   : ', eclick.button        

    def CropImage(self):
        canvas = self.widgetImage.canvas
        ax = canvas.ax
        print canvas
        print ax
        rs=RectangleSelector(ax, self.onselect, drawtype='box',
                                     rectprops = dict(facecolor='red', edgecolor = 'black', alpha=0.5, fill=True))
        print(rs)
        canvas.draw()


app = QtGui.QApplication(sys.argv)
Ui_MainWindow = Ui_MainWindow(None)
Ui_MainWindow.show()
app.exec_()

0 个答案:

没有答案