用PyQt和matplotlib Rectang裁剪图像

2024-05-19 14:43:20 发布

您现在位置:Python中文网/ 问答频道 /正文

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

UI设计是通过使用uic函数实现动态链接的 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_()

Tags: pathfromimageimportselfuimatplotlibax