class Image没有属性'fromarray'

use*_*19o 3 python multithreading opencv numpy tkinter

我正在使用OpenCV和Python Tkinter.我想将OpenCV的视频帧添加到Tkinter标签中.我使用了线程,因为我有两个循环.(我得到了这方面的指示)

当我试图运行代码它告诉我,

按任意键继续 ...线程中的异常Thread-2:Traceback(最后调用最后一次):文件"C:\ Python27\lib\threading.py",第808行,在__bootstrap_inner self.run()文件"C:\ Python27\lib\threading.py" ",第761行,在run self .__ target(*self .__ args,**self .__ kwargs)文件"c:\ users\user1\documents\visual studio 2013\Projects\defTstWindow\defT stWindow\defTstWindow.py",line 26,在makeGUI img = Image.fromarray(cv2image)AttributeError:class Image没有属性'fromarray'

我尝试使用Python类.我得到了同样的错误.

但是,如果我在一个功能运行的所有(如1日回答这个),它的正常工作.

我的代码有什么问题?

现在我有四个python模块.

1.Support.py

import cv2

global frame
frame=None
Run Code Online (Sandbox Code Playgroud)

2.CamHandler.py

import cv2
import numpy as np
import Support

cam=cv2.VideoCapture(0)


def getFrame():
    while 1:
     _,frm=cam.read()

     #cv2.imshow('frm',frm)
     Support.frame=frm

     if cv2.waitKey(1) & 0xFF == ord('q'):
        cv2.destroyAllWindows()
        break
Run Code Online (Sandbox Code Playgroud)

3.defTstWindow.py

import sys
import cv2
import Image, ImageTk

from Tkinter import *
import Support

def makeGUI():

    top=Tk()

    top.geometry("600x449+650+151")
    top.title("Test Window")
    top.configure(background="#d9d9d9")

    lblFrame = Label(top)
    lblFrame.place(relx=0.03, rely=0.04, height=411, width=544)
    lblFrame.configure(background="#d9d9d9")
    lblFrame.configure(disabledforeground="#a3a3a3")
    lblFrame.configure(foreground="#000000")
    lblFrame.configure(text='''Label''')
    lblFrame.configure(width=544)

    cv2image = cv2.cvtColor(Support.frame, cv2.COLOR_BGR2RGBA)
    img = Image.fromarray(cv2image)
    imgtk = ImageTk.PhotoImage(image=img)
    lblFrame.imgtk = imgtk
    lblFrame.configure(image=imgtk)
    #lblFrame.after(10, show_frame) 

    top.mainloop()
Run Code Online (Sandbox Code Playgroud)

4.main.py

    import CamHandler
    import defTstWindow

    import threading
    import time


    threading.Thread(target=CamHandler.getFrame).start()
    time.sleep(1)
    threading.Thread(target=defTstWindow.makeGUI).start()
Run Code Online (Sandbox Code Playgroud)

Adi*_*cha 7

更好更简单的方法是改变

import Image, ImageTk
Run Code Online (Sandbox Code Playgroud)

from PIL import Image as Img
from PIL import ImageTk
Run Code Online (Sandbox Code Playgroud)

img = Image.fromarray(cv2image)
Run Code Online (Sandbox Code Playgroud)

img = Img.fromarray(cv2image)
Run Code Online (Sandbox Code Playgroud)


War*_*ser 6

Tkinter命名空间包含类Image,所以当你写

from Tkinter import *
Run Code Online (Sandbox Code Playgroud)

你用Image一个替换了定义Tkinter.

import *可以很方便,特别是在交互式shell中工作时,但不建议用于脚本和更大的程序,正是在这个问题中所展示的原因.将导入更改为

from Tkinter import Tk, Label
Run Code Online (Sandbox Code Playgroud)

(添加该import语句所需的任何其他名称.)