Search code examples
pythoncamerakivyframe

Kivy last camera frame remains on screen


I wrote some code that starts and stops the camera.

When the user presses the "Stop Camera" button the video stops succesfully. The problem is that the last video frame remains on the screen.

How do I get a clean background after the user stops the camera?

enter image description here

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen, ScreenManager

Builder.load_string("""
<CameraScreen>:
    GridLayout:
        id: grid1
        cols: 1
        Camera:
            id: camera
            resolution: (640, 480)
            play: False
        ToggleButton:
            id: camera_button
            text: 'Start Camera'
            on_press: root.play()

<RootWidget>:
    canvas.before:
        Color:
            rgba: 1, 1, 1, 1
        Rectangle:
            pos: self.pos
            size: self.size
    CameraScreen:
        id: camera_screen
        name: "camera_screen"
""")
class CameraScreen(Screen):

    def play(self):
        if self.ids.camera.play == False:
            self.ids.camera.play = True
            self.ids.camera_button.text = "Stop Camera"
        else:
            self.ids.camera.play = False
            self.ids.camera_button.text = "Start Camera"


class RootWidget(ScreenManager):
    pass

class MainApp(App):
    def build(self):
        return RootWidget()


MainApp().run()

Solution

  • The Camera is an extension of Image, so you can change the texture of the Camera. Try something like this:

    def play(self):
        if self.ids.camera.play == False:
            self.ids.camera.texture = self.ids.camera._camera.texture
            self.ids.camera.play = True
            self.ids.camera_button.text = "Stop Camera"
        else:
            self.ids.camera.play = False
            self.ids.camera.texture = None
            self.ids.camera_button.text = "Start Camera"