在PyQt5中嵌入Matplotlib:Toolbar

2024-10-03 15:32:56 发布

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

我正在开发一个使用matplotlib和pyqt5进行图像处理的应用程序。下面是一些代码:

class MainForm(QtWidgets.QMainWindow):

    def __init__(self):
        super(MainForm, self).__init__()
        uic.loadUi("...", self)

        self.setup_ui_elements()

        self.figure = Figure(figsize=(5, 4), dpi=100)

        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NaviToolbar(self.canvas, self)

        self.MiddleRightLayout.addWidget(self.toolbar)
        self.MiddleRightLayout.addWidget(self.canvas)

    def plot(self, img):
        self.figure.figimage(img)
        self.canvas.draw()

现在,如果我加载图像并将其绘制到画布上,会出现两个问题:

  1. 将显示工具栏,但它没有效果(例如缩放、平移等)
  2. 我还没有找到一种方法来适应画布,图像通常比画布面积大得多。在

有什么想法吗?在

你好,丹尼斯


Tags: 图像selfimgmatplotlibinitdef画布图像处理
1条回答
网友
1楼 · 发布于 2024-10-03 15:32:56

一个^{}直接放置在画布上,而不使用轴。这意味着它不会自动缩放到画布或其他任何对象,也意味着缩放和平移工具没有任何效果。在

您可以使用resize参数来配置图像,self.figure.figimage(img, resize=True)让画布适合图像,如果这是您想要的。否则,您可能需要使用imshow图。在

为了使图像缩放到其原始大小,您需要对间距进行一些操作。在

import matplotlib.pyplot as plt
import numpy as np 


def plot(self, img):
    self.ax = self.figure.add_subplot(111)
    self.figure.subplots_adjust(.1,.1,.9,.9) # 10% margin around image
    h, w = np.array(img.shape[:2])/self.figure.dpi
    self.figure.set_size_inches(w/0.8,h/0.8)
    self.ax.imshow(img)
    self.ax.axis("off") # in case you want to turn the axes off
    self.canvas.draw()

相关问题 更多 >