kivymd video recording

Solutions on MaxInterview for kivymd video recording by the best coders in the world

showing results for - "kivymd video recording"
Tommaso
03 May 2019
1from kivy.app import App
2from kivy.uix.widget import Widget
3from kivy.uix.boxlayout import BoxLayout
4from kivy.uix.image import Image
5from kivy.clock import Clock
6from kivy.graphics.texture import Texture
7from kivy.properties import StringProperty, NumericProperty
8
9import cv2
10import os
11
12# Standard Video Dimensions Sizes
13STD_DIMENSIONS =  {
14    "480p": (640, 480),
15    "720p": (1280, 720),
16    "1080p": (1920, 1080),
17    "4k": (3840, 2160),
18}
19
20# Video Encoding, might require additional installs
21# Types of Codes: http://www.fourcc.org/codecs.php
22VIDEO_TYPE = {
23    'avi': cv2.VideoWriter_fourcc(*'XVID'),
24    #'mp4': cv2.VideoWriter_fourcc(*'H264'),
25    'mp4': cv2.VideoWriter_fourcc(*'XVID'),
26}
27
28class KivyCamera(BoxLayout):
29    filename = StringProperty('video.avi')
30    frames_per_second = NumericProperty(30.0)
31    video_resolution = StringProperty('720p')
32
33    def __init__(self, **kwargs):
34        super(KivyCamera, self).__init__(**kwargs)
35        self.img1=Image()
36        self.add_widget(self.img1)
37        self.capture = cv2.VideoCapture(0)
38        self.out = cv2.VideoWriter(self.filename, self.get_video_type(self.filename), self.frames_per_second, self.get_dims(self.capture, self.video_resolution))
39        Clock.schedule_interval(self.update, 1 / self.frames_per_second)
40
41    def update(self, *args):
42        ret, frame = self.capture.read()
43        self.out.write(frame)
44        buf = cv2.flip(frame, 0).tostring()
45        texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt="bgr")
46        texture.blit_buffer(buf, colorfmt="bgr", bufferfmt="ubyte")
47        self.img1.texture = texture
48
49    # Set resolution for the video capture
50    # Function adapted from https://kirr.co/0l6qmh
51    def change_resolution(self, cap, width, height):
52        self.capture.set(3, width)
53        self.capture.set(4, height)
54
55    # grab resolution dimensions and set video capture to it.
56    def get_dims(self, cap, video_resolution='1080p'):
57        width, height = STD_DIMENSIONS["480p"]
58        if self.video_resolution in STD_DIMENSIONS:
59            width, height = STD_DIMENSIONS[self.video_resolution]
60        ## change the current caputre device
61        ## to the resulting resolution
62        self.change_resolution(cap, width, height)
63        return width, height
64
65    def get_video_type(self, filename):
66        filename, ext = os.path.splitext(filename)
67        if ext in VIDEO_TYPE:
68          return  VIDEO_TYPE[ext]
69        return VIDEO_TYPE['avi']
70
71class CamApp(App):
72    def build(self):
73        return KivyCamera()
74
75if __name__ == '__main__':
76    CamApp().run()
77