我正在尝试调整我的网络摄像头输出以适应标签,但我无法真正使其正常工作。如果您决定尝试测试代码,我会在标签中添加蓝色背景作为指导您调整网络摄像头输出大小所需的大小。
代码是:
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.grid(row = 1,column = 1)
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.grid_forget()
def main():
Stop()
Reset.invoke()
stopFunc.invoke()
root = Tk()
lmain = Label(root, width = 800, height = 600, bg = "blue")
stopFunc = Button(root, text = "stop", command = Stop)
Reset = Button(root, text = "Reset", command = start)
Main = Button(root, text = "Stop", command = main)
Start = Button(root, text = "Start", command = start)
Start.grid(row = 0, column = 0)
Main.grid(row = 0, column = 1)
root.mainloop()
答案 0 :(得分:0)
我已尝试过您的代码,我在这里更改了一些代码:
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.grid(row = 1,column = 1)
def show_frame():
_, frame = cap.read()
frame = cv2.flip(frame, 1)
frame = cv2.resize(frame, (800,600))
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)
else:
cap.release()
show_frame()
def Stop():
global isrunning
isrunning = 0
lmain.grid_forget()
def main():
Stop()
#Reset.invoke()
#stopFunc.invoke()
root = Tk()
lmain = Label(root, width = 800, height = 600, bg = "blue")
stopFunc = Button(root, text = "stop", command = Stop)
Reset = Button(root, text = "Reset", command = start)
Main = Button(root, text = "Stop", command = main)
Start = Button(root, text = "Start", command = start)
Start.grid(row = 0, column = 0)
Main.grid(row = 0, column = 1)
root.mainloop()
如您所见,我添加了一行:frame = cv2.resize(frame, (800,600))
来重新调整图片大小。
我发现在添加此行之后,当我按下"停止"按钮。因此,每当您按下"停止"时,我会尝试使用cap.release()
来释放相机。按钮。但我现在没有网络摄像头来测试此代码,我无法确保它在您重新启动流时能够正常工作。希望它有所帮助。