摄像头录制与python tkinter

时间:2018-06-15 12:44:34

标签: python

我想从网络摄像头录制视频(而不是音频)。 我已经把两个按钮用于开始录制和放大停止录音。 程序启动后,从相机和相机中选择图像。在屏幕上显示。完美。 我的问题是当我点击开始录制&一段时间后停止录音, 仅创建avi文件,找到0K或6K大小。没有找到进一步的录音。

import tkinter
import cv2
import PIL.Image, PIL.ImageTk


stopb = None

class App():
    def __init__(self, window, window_title):
        self.window = window
        self.window.title = window_title
        self.ok = False
        self.video = cv2.VideoCapture(0)
        self.width = self.video.get(cv2.CAP_PROP_FRAME_WIDTH)
        self.height = self.video.get(cv2.CAP_PROP_FRAME_HEIGHT)
        #create videowriter
        self.fourcc = cv2.VideoWriter_fourcc(*'XVID')
        self.out = cv2.VideoWriter('output.avi',self.fourcc,10,(640,480))
        # Create a canvas that can fit the above video source size
        self.canvas = tkinter.Canvas(window, width=self.width, height=self.height)
        self.canvas.pack()

        self.opencamera = tkinter.Button(window, text="open camera", command=self.open_camera)
        self.opencamera.pack()
        self.closecamera = tkinter.Button(window, text="close camera", command=self.close_camera)
        self.closecamera.pack()
        self.delay = 10
        self.update()

        # After it is called once, the update method will be automatically called every delay milliseconds
        self.window.mainloop()

    def update(self):
        ret, frame = self.video.read()
        if self.ok == 'T':
            self.out.write(frame)
        if ret:
            self.photo = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(frame))
            self.canvas.create_image(0, 0, image=self.photo, anchor=tkinter.NW)

        self.window.after(self.delay, self.update)

    def open_camera(self):
        self.ok = True
        print("camera opened")
        print(self.ok)


    def close_camera(self):
        print("camera closed")
        self.ok = False
        self.video.release()
        self.out.release()

    def __del__(self):
        if self.video.isOpened():
            self.video.release()
            self.out.release()


App(tkinter.Tk(), "mywindow")

2 个答案:

答案 0 :(得分:1)

您的问题是您从未在输出中写任何内容,因为pg.DataError: ERROR: date/time field value out of range: "1529069127000" 永远不会评估为true。您应该将其更改为if self.ok == 'T',与使用if self.ok进行的操作相同。

ret

答案 1 :(得分:0)

我发现的另一个问题是 - 在点击关闭相机按钮和打开相机按钮后,新的录制不会开始。 这意味着您只能在单击关闭相机按钮之前录制捕获的第一个视频。

这是因为关闭相机函数释放了视频对象和输出对象,因此更新函数的 video.read() 将不起作用。

一个快速的解决方法是创建一个 set_camera() 方法来创建视频对象。每次在打开相机时调用此函数。

https://replit.com/@AmitYadav4/video-record-in-tkinker-canvas

相关问题