我正在尝试删除当前正在显示由OpenCV制作的网络摄像头流的Tkinter标签。我最终实现了它,但不是我想要的方式,因为它只是停止流,但流输出的最后一个图像仍然存在。代码是这样的:
from Tkinter import *
import cv2
from PIL import Image, ImageTk
def Start():
width, height = 800, 600
cap = cv2.VideoCapture(0)
cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, width)
cap.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, height)
def show_frame():
_, 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)
show_frame()
root = Tk()
lmain = Label(root)
lmain.pack(side = RIGHT)
Button1 = Button(root, text = "Start", command = Start)
Button1.pack(side = LEFT)
Button2 = Button(root, text = "Stop", command = Start)
Button2.pack(side = LEFT)
root.mainloop()
您可能会注意到我用来停止它的功能与我用来启动它的功能相同,这是因为我对如何阻止它非常无能为力。
我已经尝试过你的代码了,我在这里添加一些代码:
from Tkinter import *
import cv2
from PIL import Image, ImageTk
isrunning = 0
def Start():
global isrunning
if isrunning == 0:
width, height = 800, 600
cap = cv2.VideoCapture(0)
cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, width)
cap.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, height)
isrunning = 1
lmain.pack(side = RIGHT)
def show_frame():
_, 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)
if isrunning == 1:
lmain.after(10, show_frame)
show_frame()
def Stop():
global isrunning
isrunning = 0
lmain.pack_forget()
root = Tk()
lmain = Label(root)
Button1 = Button(root, text = "Start", command = Start)
Button1.pack(side = LEFT)
Button2 = Button(root, text = "Stop", command = Stop)
Button2.pack(side = LEFT)
root.mainloop()
你可以发现我添加了一个全局变量isrunning
来让函数show_frame
每次检查。如果变量isrunning
等于0,则函数将停止。我还添加了函数Stop
作为“停止”按钮的回调函数,其中包含代码lmain.pack_forget()
以删除标签。
由于每次单击“停止”按钮时都会删除标签,因此我会移动代码以将标签添加到Start
函数中。希望能帮助到你。
代码是:
from Tkinter import *
import cv2
from PIL import Image, ImageTk
isrunning = 0
def Start():
global isrunning
if isrunning == 0:
global cap
cap = cv2.VideoCapture(0)
isrunning = 1
lmain.pack(side = RIGHT)
def show_frame():
_, 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)
if isrunning == 1:
lmain.after(10, show_frame)
show_frame()
def Stop():
global isrunning
isrunning = 0
lmain.pack_forget()
def main():
Stop()
Button1.invoke()
Stop()
root = Tk()
lmain = Label(root)
Button1 = Button(root, text = "Start", command = Start)
Button1.pack(side = LEFT)
Button2 = Button(root, text = "Stop", command = main)
Button2.pack(side = LEFT)
root.mainloop()