Python 如何将cv2.imread与tkinter连接?

Python 如何将cv2.imread与tkinter连接?,python,tkinter,cv2,Python,Tkinter,Cv2,我的计划是为用户提供一个简单的界面来选择图像。然后,这将用于执行分析 我的问题是: 我无法获得GUI和其余代码输入之间的连接。当我直接指定文件名时,CV2.imread-only工作 解决这个问题的最好办法是什么 以下是我正在使用的代码: import cv2 import numpy as np from tkinter import * from PIL import ImageTk, Image from tkinter import filedialog from tkinter imp

我的计划是为用户提供一个简单的界面来选择图像。然后,这将用于执行分析

我的问题是:

我无法获得GUI和其余代码输入之间的连接。当我直接指定文件名时,CV2.imread-only工作

解决这个问题的最好办法是什么

以下是我正在使用的代码:

import cv2
import numpy as np
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
from tkinter import ttk


class Root (Tk):
    def __init__(self):
        super(Root, self).__init__()
        self.title("Tkinter First Window")
        self.minsize(600,300)

        self.labelFrame = ttk.LabelFrame(self, text = "Open a File")
        self.labelFrame.grid()
        self.button()

    def button(self):
        self.button = ttk.Button(self.labelFrame, text = "Browse a File", command = self.fileDialog)
        self.button.grid()

    def fileDialog(self):
        self.filename = filedialog.askopenfilename(initialdir = "C:\Python\Code\venv\Testbilder", title ="Select a File", filetype =(("jpeg", "*.jpg"), ("All Files", "*.*")))
        self.label = ttk.Label(self.labelFrame, text = "")
        self.label.grid()
        self.label.configure(text = self.filename)

def main():
    show_image = False

    **image = cv2.imread("Testbild 3%.jpg")** **I need the connection here! This needs to be the input
    blue_pixels_mask = cv2.inRange(             from the GUI selection**
        cv2.cvtColor(image, cv2.COLOR_BGR2HSV),
        np.array([100, 50, 50]),
        np.array([130, 255, 255]),
    )
    total_pixel_count = image.size // 3

    if show_image:
        cv2.imshow("Image", image)
        cv2.imshow("Mask", blue_pixels_mask)

    blue_pixel_count = cv2.countNonZero(blue_pixels_mask)
    blue_ratio = blue_pixel_count / total_pixel_count

    print(f"Das gesamte Bild besteht aus{total_pixel_count} Pixeln.")
    print(f"Das Bild beinhaltet {blue_pixel_count} blaue Pixel.")
    print(f"Der Blauanteil beträgt damit: {blue_ratio:0.2%}.")

    if show_image:
        cv2.waitKey(0)
        cv2.destroyAllWindows()


if __name__ == "__main__":
    main()

root =Root()
root.mainloop()

您应该调用
main()
内部
fileDialog()
并将文件名传递给它。您应该调用
main()
内部
fileDialog()
并将文件名传递给它。