Python中AttributeError: 'list' object has no attribute 'read',请求大佬帮忙

qq_47623455 2021-07-31 21:24:42

import wx
from test import evaluate_one_image
from PIL import Image
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import os


class HelloFrame(wx.Frame):

    def __init__(self, *args, **kw):
        super(HelloFrame, self).__init__(*args, **kw)

        pnl = wx.Panel(self)

        self.pnl = pnl
        st = wx.StaticText(pnl, label="花朵识别", pos=(200, 0))
        font = st.GetFont()
        font.PointSize += 10
        font = font.Bold()
        st.SetFont(font)

        # 选择图像文件按钮
        btn = wx.Button(pnl, -1, "select")
        btn.Bind(wx.EVT_BUTTON, self.OnSelect)

        self.makeMenuBar()

        self.CreateStatusBar()
        self.SetStatusText("Welcome to flower world")

    def makeMenuBar(self):
        fileMenu = wx.Menu()
        helloItem = fileMenu.Append(-1, "&Hello...\tCtrl-H",
                                    "Help string shown in status bar for this menu item")
        fileMenu.AppendSeparator()

        exitItem = fileMenu.Append(wx.ID_EXIT)
        helpMenu = wx.Menu()
        aboutItem = helpMenu.Append(wx.ID_ABOUT)

        menuBar = wx.MenuBar()
        menuBar.Append(fileMenu, "&File")
        menuBar.Append(helpMenu, "Help")

        self.SetMenuBar(menuBar)

        self.Bind(wx.EVT_MENU, self.OnHello, helloItem)
        self.Bind(wx.EVT_MENU, self.OnExit, exitItem)
        self.Bind(wx.EVT_MENU, self.OnAbout, aboutItem)

    def OnExit(self, event):
        self.Close(True)

    def OnHello(self, event):
        wx.MessageBox("Hello again from wxPython")

    def OnAbout(self, event):
        """Display an About Dialog"""
        wx.MessageBox("This is a wxPython Hello World sample",
                      "About Hello World 2",
                      wx.OK | wx.ICON_INFORMATION)

    def OnSelect(self, event):
        wildcard = "image source(*.jpg)|*.jpg|" \
                   "Compile Python(*.pyc)|*.pyc|" \
                   "All file(*.*)|*.*"
        dialog = wx.FileDialog(None, "Choose a file", os.getcwd(),
                               "", wildcard, wx.FD_OPEN)
        if dialog.ShowModal() == wx.ID_OK:
            print(dialog.GetPaths())

            img = Image.open(dialog.GetPaths())
            imag = img.resize([64, 64])
            image = np.array(imag)
            result = evaluate_one_image(image)
            result_text = wx.StaticText(self.pnl, label=result, pos=(320, 0))
            font = result_text.GetFont()
            font.PointSize += 8
            result_text.SetFont(font)
            self.initimage(name=dialog.GetPaths())

    # 生成图片控件
    def initimage(self, name):
        imageShow = wx.Image(name, wx.BITMAP_TYPE_ANY)
        sb = wx.StaticBitmap(self.pnl, -1, imageShow.ConvertToBitmap(), pos=(0, 30), size=(600, 400))
        return sb


if __name__ == '__main__':
    app = wx.App()
    frm = HelloFrame(None, title='flower world', size=(1000, 600))
    frm.Show()
    app.MainLoop()

 

D:\anaconda\envs\tf\python.exe C:/Users/86185/Desktop/GitHub/four_flower/gui.py
['C:\\Users\\86185\\Desktop\\GitHub\\玫瑰花.jpg']
Traceback (most recent call last):
  File "D:\anaconda\envs\tf\lib\site-packages\PIL\Image.py", line 2972, in open
    fp.seek(0)
AttributeError: 'list' object has no attribute 'seek'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/86185/Desktop/GitHub/four_flower/gui.py", line 76, in OnSelect
    img = Image.open(dialog.GetPaths())
  File "D:\anaconda\envs\tf\lib\site-packages\PIL\Image.py", line 2974, in open
    fp = io.BytesIO(fp.read())
AttributeError: 'list' object has no attribute 'read'

Process finished with exit code 0
 

...全文
7635 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
crifan 2021-08-01
  • 打赏
  • 举报
回复 2

从你的错误AttributeError: 'list' object has no attribute 'read',以及错误相关代码是:
img = Image.open(dialog.GetPaths())
可以看出:
你用dialog.GetPaths()返回了一个list列表,传入了Image.open(),所以报错:
因为Image.open()希望传入的是 (单个的)图片文件的文件路径
比如PIL Image的例子:

from PIL import Image
with Image.open("hopper.jpg") as im:
    im.rotate(45).show()

所以,此处问题就变成了:
如何改代码,确保你传入的代码是单个图片文件的路径?

别人让你把 dialog.GetPaths()改为dialog.GetPaths()[0]
-》这只能:让弹框选中的多个文件,只返回第一个
-》会导致(1)其他选中的文件,被忽略掉 (2)第一个选中的文件,你自己要确保是图片文件。后续代码才不会报错。

-》你后续的报错:
tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value local4/weights [[node local4/weights/read (defined at C:\Users\86185\Desktop\GitHub\four_flower\model.py:67) ]]
我暂不确定是否就是,非图片导致的相关问题。

但是你既然(代码中)要处理(单个)图片,那就最好,只允许用户选择图片,且是单个图片文件
所以代码应该改为:
wx.FileDialog — wxPython Phoenix 4.1.2a1 documentation
中的

GetPath
Returns the full path (directory and filename) of the selected file.

而不是:

GetPaths
Returns a list of the full paths of the files chosen. This function

即:
dialog.GetPaths() 改为 dialog.GetPath()

以及为了确保,选择的图片文件(而不是其他类型文件),那么文件过滤条件,就应该只保留图片的
即,把

wildcard = "image source(*.jpg)|*.jpg|" \
                   "Compile Python(*.pyc)|*.pyc|" \
                   "All file(*.*)|*.*"

改为:

wildcard = "image source(*.jpg)|*.jpg|"

注:如果要支持其他如png等格式,你自己再加对应过滤条件。


总结:
改动:

  1. dialog.GetPaths() 改为 dialog.GetPath():只选择单个文件
  2. wildcard改为:wildcard = "image source(*.jpg)|*.jpg|":确保只显示、列出、选择(jpg)图片文件(而不包括其他非图片类文件)

估计就不会报错了。

如果还有错,应该也是其他方面的错误了。

m0_57901298 2021-08-01
  • 打赏
  • 举报
回复

76行
试试改成 img = Image.open(dialog.GetPaths()[0])

qq_47623455 2021-08-01
  • 举报
回复
@m0_57901298 谢谢大佬,改完后还是有其他地方报错了
qq_47623455 2021-08-01
  • 举报
回复
@m0_57901298 Traceback (most recent call last): File "C:/Users/86185/Desktop/GitHub/four_flower/gui.py", line 79, in OnSelect result = evaluate_one_image(image) File "C:\Users\86185\Desktop\GitHub\four_flower\test.py", line 55, in evaluate_one_image prediction = sess.run(logit, feed_dict={x: image_array}) File "D:\anaconda\envs\tf\lib\site-packages\tensorflow\python\client\session.py", line 950, in run run_metadata_ptr) File "D:\anaconda\envs\tf\lib\site-packages\tensorflow\python\client\session.py", line 1173, in _run feed_dict_tensor, options, run_metadata) File "D:\anaconda\envs\tf\lib\site-packages\tensorflow\python\client\session.py", line 1350, in _do_run run_metadata) File "D:\anaconda\envs\tf\lib\site-packages\tensorflow\python\client\session.py", line 1370, in _do_call raise type(e)(node_def, op, message) tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value local4/weights [[node local4/weights/read (defined at C:\Users\86185\Desktop\GitHub\four_flower\model.py:67) ]] Original stack trace for 'local4/weights/read': File "C:/Users/86185/Desktop/GitHub/four_flower/gui.py", line 97, in <module> app.MainLoop() File "D:\anaconda\envs\tf\lib\site-packages\wx\core.py", line 2237, in MainLoop rv = wx.PyApp.MainLoop(self) File "C:/Users/86185/Desktop/GitHub/four_flower/gui.py", line 79, in OnSelect result = evaluate_one_image(image) File "C:\Users\86185\Desktop\GitHub\four_flower\test.py", line 33, in evaluate_one_image logit = model.inference(image, BATCH_SIZE, N_CLASSES) File "C:\Users\86185\Desktop\GitHub\four_flower\model.py", line 67, in inference name='weights', dtype=tf.float32) File "D:\anaconda\envs\tf\lib\site-packages\tensorflow\python\ops\variables.py", line 259, in __call__ return cls._variable_v1_call(*args, **kwargs) File "D:\anaconda\envs\tf\lib\site-packages\tensorflow\python\ops\variables.py", line 220, in _variable_v1_call shape=shape) File "D:\anaconda\envs\tf\lib\site-packages\tensorflow\python\ops\variables.py", line 198, in <lambda> previous_getter = lambda **kwargs: default_variable_creator(None, **kwargs) File "D:\anaconda\envs\tf\lib\site-packages\tensorflow\python\ops\variable_scope.py", line 2511, in default_variable_creator shape=shape) File "D:\anaconda\envs\tf\lib\site-packages\tensorflow\python\ops\variables.py", line 263, in __call__ return super(VariableMetaclass, cls).__call__(*args, **kwargs) File "D:\anaconda\envs\tf\lib\site-packages\tensorflow\python\ops\variables.py", line 1568, in __init__ shape=shape) File "D:\anaconda\envs\tf\lib\site-packages\tensorflow\python\ops\variables.py", line 1755, in _init_from_args self._snapshot = array_ops.identity(self._variable, name="read") File "D:\anaconda\envs\tf\lib\site-packages\tensorflow\python\util\dispatch.py", line 180, in wrapper return target(*args, **kwargs) File "D:\anaconda\envs\tf\lib\site-packages\tensorflow\python\ops\array_ops.py", line 86, in identity ret = gen_array_ops.identity(input, name=name) File "D:\anaconda\envs\tf\lib\site-packages\tensorflow\python\ops\gen_array_ops.py", line 4252, in identity "Identity", input=input, name=name) File "D:\anaconda\envs\tf\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 788, in _apply_op_helper op_def=op_def) File "D:\anaconda\envs\tf\lib\site-packages\tensorflow\python\util\deprecation.py", line 507, in new_func return func(*args, **kwargs) File "D:\anaconda\envs\tf\lib\site-packages\tensorflow\python\framework\ops.py", line 3616, in create_op op_def=op_def) File "D:\anaconda\envs\tf\lib\site-packages\tensorflow\python\framework\ops.py", line 2005, in __init__ self._traceback = tf_stack.extract_stack()

37,741

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧