python - 浏览全局 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()
谁能给我解释一下我在哪里搞砸了以及如何解决它,谢谢。
解决方案
您的问题可能是askopenfile
使用open(selected_file)
.
您需要file_name.name
获取其名称(作为字符串)。
或用于askopenfilename
获取名称而不是文件对象。
推荐阅读
- flutter - StreamBuilder 完全加载后有没有办法获得回调?
- amazon-web-services - 当节点数超过一个时,Redislabs UI 日志记录错误
- asp.net-core - 网络核心中的数据注释不适用于列表
- javascript - Nodemails 给我 TypeError [ERR_INVALID_ARG_TYPE]:“路径”参数必须是字符串类型。接收类型未定义
- python - 在此类查询中查找或聚合
- grub - 创建一个自动检测 EFI 系统并启动第一个系统的 grub 脚本
- api - 如何使用 Vtiger API 在修改时间上查询模块(潜力)
- python - 英特尔实感 - 在两个 numpy 数组中对齐深度和颜色
- python - discord.ext.commands.errors.CommandNotFound:找不到命令“平衡”
- php - 具有 enctype 的表单在请求中返回空文件