Python 2.7 CV2& Tkinter与网络摄像头

时间:2015-08-28 13:14:58

标签: python python-2.7 opencv tkinter

我正在使用Tkinter制作一个gui来显示usb相机的输出。用于显微镜实验的想法是gui显示低分辨率的直播流,但是在点击按钮时拍摄高分辨率图像。我已经能够使用我的笔记本电脑的内置网络摄像头(VideoCapture(0))获得代码,但是当我尝试将代码用于预期的网络摄像头(https://www.leopardimaging.com/uploads/LI-OV5640-USB-72_datasheet.pdf - VideoCapture(1))时,它会崩溃。 代码是这样的:

import Tkinter as tk
import cv2
import cv2.cv as cv
import numpy as np
from PIL import Image, ImageTk

global counter
counter = 0
global save_dir
save_dir = "C:/Users/etc..."
global runner
runner = 50
global run_num
run_num = "50"
##########################################################################
global hi_w, hi_h
global lo_w, lo_h
hi_w, hi_h = 640,480 # Camera intended resolution 2592,1944
lo_w, lo_h = 320,240 # Camera intended resolution 640,480
cap = cv2.VideoCapture(1)
cap.set(3, lo_w)
cap.set(4, lo_h)
cap.set(5,15)
##########################################################################
# Define the Tkinter functions

#-- QUIT_ --#
#-----------#
def quit_(root):
    root.destroy()    
#---------------------
#-- FUNCTION1 --#
#---------------#
def function1(root):
    global counter
    counter = 1    
#---------------------
#-- FUNCTION2 --#
#---------------#
def function2(root):
    global counter
    counter = 2    
#---------------------
#-- FUNCTION3 --#
#---------------#
def function3(root):
    global counter
    counter = 3    
#---------------------
def capture(filename):
    print 'capturing'
    global hi_w, hi_h, lo_w, lo_h
    cap.set(3, hi_w)
    cap.set(4, hi_h)
    flag2, frame2 = cap.read()
    frame2 = cv2.flip(frame2, 1)
    print 'writing'
    cv2.imwrite(filename, frame2)
    print 'resetting'
    cap.set(3, lo_w)
    cap.set(4, lo_h)
    del flag2, frame2
    global counter
    counter = 0

def show_frame():
    #Set up dummy frame
    global counter, save_dir, runner, run_num
    if counter == 1:
        flag,frame = cap.read()
        filename = save_dir + "z01_" + run_num + ".jpeg"
        capture(filename)
    elif counter == 2:
        flag, frame = cap.read()
        filename = save_dir + "z02_" + run_num + ".jpeg"
        capture(filename)
    elif counter == 3:
        flag, frame = cap.read()
        filename = save_dir + "z03_" + run_num + ".jpeg"
        capture(filename)
        runner = runner + 1
        run_num = '{0:02d}'.format(runner)
        counter = 0
    else:
            flag, frame = cap.read()
            frame = cv2.flip(frame, 1)

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


if __name__ == '__main__':
    root = tk.Tk()
    lmain = tk.Label(master=root)
    lmain.grid(column=0, rowspan=4, padx=5, pady=5)

    button1 = tk.Button(master=root, text='Function 1', command=lambda: function1(root))
    button1.grid(column=1, columnspan=2, row=0, padx=5, pady=5)
    button2 = tk.Button(master=root, text='Function 2', command=lambda: function2(root))
    button2.grid(column=1, columnspan=2, row=1, padx=5, pady=5)
    button3 = tk.Button(master=root, text='Function 3', command=lambda: function3(root))
    button3.grid(column=1, columnspan=2, row=2, padx=5, pady=5)
    quit_button = tk.Button(master=root, text='Quit',bg="red3", fg="white", command=lambda: quit_(root))
    quit_button.grid(column=1, row=3, padx=5, pady=5)

    show_frame()
    root.mainloop()
    cap.release()

按下第一个按钮后程序崩溃并出现以下错误

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
    return self.func(*args)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 533, in callit
    func(*args)
  File "C:/Users/.../LI_USB_GUI_RR_worksWithInBuiltCam2.py", line 109, in show_frame
    cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
error: ..\..\..\..\opencv\modules\imgproc\src\color.cpp:3648: error: (-215) scn == 3 || scn == 4 in function cv::cvtColor

要写入的文件大小为零字节。应该在那里供给显示器的框架已经变空,尽管相机仍然可以通过外壳进行控制。我真的很困惑为什么内置摄像头可以工作,但USB不会使用相同的代码。

请帮忙......

1 个答案:

答案 0 :(得分:2)

好的,我想我已经解决了这个问题。 基本上,程序在更改分辨率之后不断尝试要求相机在准备好之前显示下一帧。因此它返回None并且程序崩溃了。我通过制作与预览图像大小相同的虚拟帧来解决它,然后用相机中的最后一个有效帧填充它。当程序正在录制高分辨率静止图像时,将显示最后一帧。此外,为了给程序足够的时间来记录图像,我设置了一个while循环,为摄像机提供一段设定的时间来自行配置并记录图像。如果出现故障并且超时,我可以创建一种安全关闭程序的方法。新代码如下所示,除了处理异常 - 将安全关闭应用程序的样板文件可以放在那里。

import Tkinter as tk
import cv2
import cv2.cv as cv
import numpy as np
from PIL import Image, ImageTk
import time

global save_dir
save_dir = "C:/Users/.../"
global runner
runner = 00
global run_num
run_num = "00"

##########################################################################
##########################################################################
global hi_w, hi_h
global lo_w, lo_h
hi_w, hi_h = 2592,1944
lo_w, lo_h = 640,480
#Set up dummy frame
global last_frame
last_frame = np.zeros((lo_h, lo_w, 3), dtype=np.uint8)
global cap
cap = cv2.VideoCapture(1)
cap.set(3, lo_w)
cap.set(4, lo_h)

##########################################################################
##########################################################################
# Define the Tkinter functions

#-- QUIT_ --#
#-----------#
def quit_(root):
    root.destroy()

#---------------------


#-- FUNCTION1 --#
#---------------#
def function1(root):
    global save_dir, run_num
    filename = save_dir + "z01_" + run_num + ".jpeg"
    capture(filename)

#---------------------


#-- FUNCTION2 --#
#---------------#
def function2(root):
    global save_dir, run_num
    filename = save_dir + "z02_" + run_num + ".jpeg"
    capture(filename)

#---------------------


#-- FUNCTION3 --#
#---------------#
def function3(root):
    global save_dir, runner, run_num
    filename = save_dir + "z03_" + run_num + ".jpeg"
    capture(filename)
    runner = runner + 1
    run_num = '{0:02d}'.format(runner)

#---------------------

def capture(filename):
    print 'capturing'
    cap.set(3, hi_w)
    cap.set(4, hi_h)
    print time.time()

    timeout = time.time() + 30
    while time.time() < timeout:
        flag2, frame2 = cap.read()
        if flag2:
            frame2 = cv2.flip(frame2,1)
            cv2.imwrite(filename, frame2)
            cap.set(3, lo_w)
            cap.set(4, lo_h)
            time.sleep(1)
            global counter
            counter = 0
            break
        else:
            time.sleep(1)
    else:
        <code to handle timeout appropriately>

#---------------------       

def show_frame():
    global counter, save_dir, runner, run_num
    flag, frame = cap.read()
    frame = cv2.flip(frame, 1)
    if flag is None:
        print "Major error!"
        <code to handle exception>
    elif flag:
        global last_frame
        last_frame = frame.copy()
    else:
        print "Cant process the image"
        <code to handle exception>

    cv2image = cv2.cvtColor(last_frame, cv2.COLOR_BGR2RGBA)
    img = Image.fromarray(cv2image)
    imgtk = ImageTk.PhotoImage(image=img)
    lmain.imgtk = imgtk
    lmain.configure(image=imgtk)
    lmain.after(10, show_frame)



##########################################################################
##########################################################################


if __name__ == '__main__':
    root = tk.Tk()
    lmain = tk.Label(master=root)
    lmain.grid(column=0, rowspan=4, padx=5, pady=5)

    button1 = tk.Button(master=root, text='Function 1', command=lambda: function1(root))
    button1.grid(column=1, columnspan=2, row=0, padx=5, pady=5)
    button2 = tk.Button(master=root, text='Function 2', command=lambda: function2(root))
    button2.grid(column=1, columnspan=2, row=1, padx=5, pady=5)
    button3 = tk.Button(master=root, text='Function 3', command=lambda: function3(root))
    button3.grid(column=1, columnspan=2, row=2, padx=5, pady=5)
    quit_button = tk.Button(master=root, text='Quit',bg="red3", fg="white", command=lambda: quit_(root))
    quit_button.grid(column=1, row=3, padx=5, pady=5)


    show_frame()
    root.mainloop()
    cap.release()

感谢所有帮助过的人。