首页 > 解决方案 > Python PIL.Image 模块似乎与 tkinter 模块冲突(AttributeError: type object 'Image' has no attribute 'open')

问题描述

谁能帮我理解为什么我得到“AttributeError:类型对象'Image'没有属性'open'”这个代码。在我看来它真的很干净。奇怪的是,我还尝试在从函数 clicked() 读取时访问全局 var,但这没有用(我现在评论了这些行,但代码中报告了错误)。这可能是一个线索!然而,我迷路了!

非常感谢你的帮助!

from __future__ import print_function
import binascii
import struct
from PIL import Image, ImageTk
#import Image
import numpy as np
import scipy
import scipy.misc
import scipy.cluster

from tkinter import *

NUM_CLUSTERS = 5


#im=3  #just for testing access to global vars, in second line int he function . Oddly Failed:  "UnboundLocalError: local variable 'im' referenced before assignment"



window = Tk()
window.title("Welcome to LikeGeeks app")
window.geometry('350x200')
lbl = Label(window, text="Hello")
lbl.grid(column=0, row=0)




def clicked():
    print('reading image')
    #print(im)  #just for testing access to global vars . Oddly Failed:  "UnboundLocalError: local variable 'im' referenced before assignment"
    im = Image.open('image.jpg')
    im = im.resize((150, 150))      # optional, to reduce time
    ar = np.asarray(im)
    shape = ar.shape
    ar = ar.reshape(scipy.product(shape[:2]), shape[2]).astype(float)

    print('finding clusters')
    codes, dist = scipy.cluster.vq.kmeans(ar, NUM_CLUSTERS)
    print('cluster centres:\n', codes)

    vecs, dist = scipy.cluster.vq.vq(ar, codes)         # assign codes
    counts, bins = scipy.histogram(vecs, len(codes))    # count occurrences

    index_max = scipy.argmax(counts)                    # find most frequent
    peak = codes[index_max]
    colour = binascii.hexlify(bytearray(int(c) for c in peak)).decode('ascii')
    print('most frequent is %s (#%s)' % (peak, colour))

    lbl.configure(text='most frequent is &peak &colour ')

    return

btn = Button(window, text="Click Me to load image.jpg", command=clicked)
btn.grid(column=1, row=0)
window.mainloop()

标签: pythontkinterpython-imaging-librarypython-module

解决方案


推荐阅读