使用 cv2.imshow 让 tkinter 按钮显示图像?

问题描述 投票:0回答:1

我正在尝试制作一个 GUI,我可以通过单击按钮选择图像,然后通过单击另一个按钮显示图像。这是我的代码:

import tkinter as tk
from tkinter import ttk
import tkinter.filedialog as fd
import cv2

class LabelClass:
    def labelframe(root, text, row, col, padx, pady):
        label_frame = tk.LabelFrame(root, text=text)
        label_frame.grid(row=row, column=col, padx=padx, pady=pady)
        return label_frame

    def label(root, text, row, col, padx, pady):
        lab = tk.Label(root, text=text)
        lab.grid(row=row, column=col, padx=padx, pady=pady)
        return lab

class ComboBox:
    def combobox(root, values, row, col, padx, pady):
        box = ttk.Combobox(root, values=values)
        box.grid(row=row, column=col, padx=padx, pady=pady)
        return box

class ButtonClass:
    def button(root, text, command, row, col, padx, pady):
        button = tk.Button(root, text=text, command=command)
        button.grid(row=row, column=col, sticky="news", padx=padx, pady=pady)

class ButtonFunction:
    def select_image(label):
        filepath = fd.askopenfilename()
        filename = filepath.split("/")[-1]
        text = "Selected image: {}".format(filename)
        label.config(text=text)
        return filepath
    
    def show_image(image_path):
        cv2.imshow("Image", image_path)

class Main:
    def __init__(self):
        self.root = tk.Tk()
        self.frame = tk.Frame(self.root)
        self.frame.pack()

    def application(self):
        padx, pady = 15, 10
        labelframe1 = LabelClass.labelframe(self.frame, "Select image", 0, 0, padx, pady)
        label1 = LabelClass.label(labelframe1, "Selected image: -", 0, 0, padx, pady)
        img = lambda: ButtonFunction.select_image(label1)
        img_button = ButtonClass.button(labelframe1, "Select image", img, 0, 1, padx, pady)

        labelframe2 = LabelClass.labelframe(self.frame, "Show result", 1, 0, padx, pady)
        show = lambda: ButtonFunction.show_image(img)
        defect_button = ButtonClass.button(labelframe2, "Show image", show, 0, 0, padx, pady)

        self.root.mainloop()

M = Main()
M.application()

因此,代码打开一个 GUI,然后我从

Select image
按钮选择图像,然后我想用
Show image
按钮显示图像。但这不起作用。我收到此错误:

cv2.error: OpenCV(4.9.0) :-1: error: (-5:Bad argument) in function 'imshow'
> Overload resolution failed:
>  - mat is not a numpy array, neither a scalar
>  - Expected Ptr<cv::cuda::GpuMat> for argument 'mat'
>  - Expected Ptr<cv::UMat> for argument 'mat'

此错误意味着什么以及如何修复我的代码?

python opencv user-interface tkinter button
1个回答
0
投票

cv2.imshow() 函数需要 numpy 数组形式的图像,但您要向它传递一个字符串(文件路径)。您需要使用 cv2.imread() 将图像读入 numpy 数组,然后才能显示它。

def show_image(image_path):
    image = cv2.imread(image_path)  # Read the image file into a numpy array
    cv2.imshow("Image", image)
© www.soinside.com 2019 - 2024. All rights reserved.