Can't adding my camera widget to the Screen to make the camera open in kivymd form .kv

Question:

I made a WebHomeScreen in which i make a two functions for my webcam to start/launch and read the live feed using opencv when i run my code the webcam starts but its not showing on the app screen.

Below is the code of my main.py file.

`

class WebCamScreen(Screen):

    def do_start(self):
        self.capture = cv2.VideoCapture(0)
        Clock.schedule_interval(self.load_video, 1.0 / 24.0)

    def load_video(self, *args):
        ret, frame = self.capture.read()
        # self.image_frame = frame
        buffer = cv2.flip(frame, 0).tostring()
        image_texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt="bgr")
        image_texture.blit_buffer(buffer, colorfmt="bgr", bufferfmt="ubyte")
        self.texture = image_texture


class MainApp(MDApp):

def build(self):
    screen_manger = ScreenManager()
    screen_manger.add_widget(LoginScreen(name="login"))
    screen_manger.add_widget(RegistrationScreen(name="registration"))
    screen_manger.add_widget(HomeScreen(name="home"))
    screen_manger.add_widget(WebCamScreen(name="camera"))

    return screen_manger
if __name__ == "__main__":
    MainApp().run()

`

and my .kv file code is

<WebCamScreen>
MDBoxLayout:
    MDRaisedButton:
        text: "Start Camera"
        size_hint_x: None
        size_hint_y: None
        md_bg_color: "orange"
        pos_hint: {"center_x": 0.2, "center_y": 0.5}
        on_press:
            root.do_start()

How can i put my webcam which is a live feed on the this WebCamScreen

Asked By: Jamal Khan

||

Answers:

You can just add an Image to your kv:

<WebCamScreen>:
    MDBoxLayout:
        MDRaisedButton:
            text: "Start Camera"
            size_hint_x: None
            size_hint_y: None
            md_bg_color: "orange"
            pos_hint: {"center_x": 0.2, "center_y": 0.5}
            on_press:
                root.do_start()
        Image:
            id: img

Then set the texture of that Image to the camera output:

def load_video(self, *args):
    ret, frame = self.capture.read()
    # self.image_frame = frame
    buffer = cv2.flip(frame, 0).tostring()
    image_texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt="bgr")
    image_texture.blit_buffer(buffer, colorfmt="bgr", bufferfmt="ubyte")
    self.ids.img.texture = image_texture
Answered By: John Anderson
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.