首页 > 解决方案 > 浏览全局 file_name 变量中的图像后 imread 出错

问题描述

我用 tkinter 创建了一个简单的用户界面,允许用户浏览图像,当按下“计算角度”按钮时,它应该打印所选图像中两条线之间的角度,并在 python 控制台上打印角度值但我收到了这些错误:

File "D:\Python\PyFolder\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "D:/PyCharm/PyCharm Community Edition 2018.3.5/PyProjetcs/angelTest/tkTest.py", line 21, in calculate
    image = imread(file_name)
  File "D:\PyCharm\PyCharm Community Edition 2018.3.5\PyProjetcs\angelTest\venv\lib\site-packages\matplotlib\pyplot.py", line 2152, in imread
    return matplotlib.image.imread(fname, format)
  File "D:\PyCharm\PyCharm Community Edition 2018.3.5\PyProjetcs\angelTest\venv\lib\site-packages\matplotlib\image.py", line 1369, in imread
    return handler(fname)
OSError: failed to read file

这是我的python代码:

from tkinter import *
import tkinter.messagebox
from tkinter import filedialog
import numpy as np
from skimage.transform import (hough_line, hough_line_peaks)
from pylab import imread


root = Tk()
root.geometry('270x250')
root.title("Angle Calculation")
root.iconbitmap(r'D:\\Pictures\\iconTest.ico')


def browse_file():
    global file_name
    file_name = filedialog.askopenfile()


def calculate():
    image = imread(file_name)
    image = np.mean(image, axis=2)

    h, theta, d = hough_line(image)

    angle = []
    dist = []

    for _, a, d in zip(*hough_line_peaks(h, theta, d)):
        angle.append(a)
        dist.append(d)

    angle = [a * 180 / np.pi for a in angle]
    angle_reel = np.max(angle) - np.min(angle)

    print(angle_reel)


btn1 = Button(root, command=browse_file, text='Browse Image').pack()

btn2 = Button(root, command=calculate, text='Calculate angle').pack()

label1 = Label(root, text='The angle is equal to:').pack()
text = Entry().pack()


root.mainloop()

谁能给我解释一下我在哪里搞砸了以及如何解决它,谢谢。

标签: pythonimagetkinterimread

解决方案


您的问题可能是askopenfile使用open(selected_file).
您需要file_name.name获取其名称(作为字符串)。

或用于askopenfilename获取名称而不是文件对象。


推荐阅读