Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· openaiHugging Face Suzhen/CodeChat

from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen from…

  1. User

    from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.button import Button from kivy.uix.image import Image from kivy.graphics.texture import Texture from kivy.clock import Clock from kivy.metrics import dp from kivy.properties import StringProperty import JsonUtl as jsonutil import cv2

    from kivy.uix.boxlayout import BoxLayout

    class MainScreen(Screen): ServerListVar = jsonutil.OpenJsontoArray() BtnId = 0 DelBtnId = 0 textures = []

    def __init__(self, **kw):
        super().__init__(**kw)
        for i in range (0,len(self.ServerListVar)):
            self.CreateButtons(i)
    
    def Clicked(self,widget):
        Adress = self.ids.StreamAdress
        if not Adress.text == "":
            self.ServerListVar.append(Adress.text.strip())
            jsonutil.SaveArraytoJson(self.ServerListVar)
            self.CreateButtons(len(self.ServerListVar)- 1)
    
    def CamSelectButtonPressed(self,x):
            app = App.get_running_app()
            app.data = self.ServerListVar[x]
            app.root.current = "Stream"  
    
    def CamDeleteButtonPressed(self,x):
        del self.ServerListVar[x]
        self.ids.CamSelectStackLayout.clear_widgets()
        jsonutil.SaveArraytoJson(self.ServerListVar)
        self.ServerListVar = jsonutil.OpenJsontoArray() 
        self.BtnId = 0
        self.DelBtnId = 0
        for i in range (0,len(self.ServerListVar)):
            self.CreateButtons(i)
    
    def CreateButtons(self, i):
        b = Button(size_hint = (None, None),width= dp(200), height = dp(200),text = self.ServerListVar[i], font_size = 10)
        b2 = Button(size_hint = (None, None),width = dp(50), height = dp(200), background_color = (1,0,0,1))
        b.bind(on_press=lambda instance, button_id=self.BtnId: self.CamSelectButtonPressed(button_id))
        self.BtnId = self.BtnId + 1
        self.ids.CamSelectStackLayout.add_widget(b) 
        b2.bind(on_press=lambda instance, button_id=self.DelBtnId: self.CamDeleteButtonPressed(button_id))
        self.DelBtnId = self.DelBtnId + 1
        self.ids.CamSelectStackLayout.add_widget(b2) 
    

    class StreamView(Screen): output = StringProperty() event = None def on_enter(self): app = App.get_running_app() self.output = app.data self.capture = cv2.VideoCapture(self.output)
    b = Button(size_hint = (0.05, 0.05), pos_hint = {"top":1}, background_color = (1,0,0,1)) b.bind(on_press=lambda instance, button_id="i": gotomainscreen(button_id)) self.add_widget(b) self.image = Image() self.add_widget(self.image) self.event = Clock.schedule_interval(self.update, 1.0 / 30.0)

        def gotomainscreen(x):
            app = App.get_running_app()
            app.root.current = "Main"
    
    def update(self, dt):
        ret, frame = self.capture.read()
        if ret:
            buf = cv2.flip(frame, 0).tostring()  
            texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='bgr')
            texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte')
            self.image.texture = texture
    
    def on_leave(self):
        self.capture.release()
        self.event.cancel()
        cv2.destroyAllWindows()
    

    class ScreenMan(ScreenManager): pass

    class IPCAMApp(App): def build(self): sm = ScreenMan() sm.add_widget(MainScreen(name="Main")) sm.add_widget(StreamView(name="Stream")) sm.current = "Main" return sm

    if name == "main": IPCAMApp().run()

  2. Assistant

    Your code is creating a Kivy application that allows users to enter the IP addresses of IP cameras and view their video streams. It uses OpenCV for the video processing and Kivy for creating the user interface.

    Here's a brief overview of how your code works:

    • MainScreen: This screen is the main screen where users can enter the IP addresses of the cameras they'd like to view. It displays a list of buttons corresponding to the IP addresses entered by users and saved in a JSON file. Users can also delete the IP addresses from the list.

    • StreamView: This screen shows the video stream from the selected camera.

    • ScreenMan: It's a ScreenManager that allows switching between the MainScreen and StreamView.

    • IPCAMApp: This class is the main Kivy app that puts everything together and runs the app.

    When the app runs, it first displays the MainScreen, allowing users to enter the IP addresses of the cameras. When a user clicks on a button corresponding to a camera, it switches to the StreamView, where the video stream from the camera is displayed. Users can also go back to the MainScreen from the StreamView.

    Here's a breakdown of the classes and methods in the code:

    • MainScreen

      • __init__(): Initializes the MainScreen and creates buttons for the camera IP addresses saved in the JSON file.
      • Clicked(): Adds a new IP address to the list and saves it to the JSON file.
      • CamSelectButtonPressed(): Switches to the StreamView screen and starts displaying the video stream from the selected camera.
      • CamDeleteButtonPressed(): Deletes the selected IP address from the list and updates the JSON file.
      • CreateButtons(): Creates buttons for the camera IP addresses in the list.
    • StreamView

      • on_enter(): Sets up the video stream capture and adds the image widget to the screen.
      • update(): Updates the image widget with the latest frame from the video stream.
      • on_leave(): Releases the video capture and cancels the scheduled update events.
    • ScreenMan: Inherits from ScreenManager and is simply an empty subclass.

    • IPCAMApp: Inherits from kivy.app.App and defines the build() method for creating the app with the screens added to the ScreenManager.

  3. User

    can you modify CreateButtons function to add thumbnails of selected stream on buttons ?

  4. Assistant

    In the code below, I have updated the CreateButtons() function to display the thumbnails of the selected streams on the buttons. This function captures the first frame of the video stream to create the thumbnail as an Image widget and then adds it to the button. Here's the updated code:

    import threading
    import time
    
    class MainScreen(Screen):
        # ... other code ...
    
        def CreateButtons(self, i):
            cap = cv2.VideoCapture(self.ServerListVar[i])
    
            # Capture the first frame as a thumbnail
            ret, frame = cap.read()
    
            if ret:
                buf = cv2.flip(frame, 0).tostring()
                texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='bgr')
                texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte')
                thumbnail = Image(texture=texture)
            else:
                thumbnail = Image(color=(0, 0, 0, 0.5))
    
            cap.release()
    
            # Create the button with the thumbnail as the background image
            b = Button(size_hint=(None, None), width=dp(200), height=dp(200),
                       background_normal="",)
            b.add_widget(thumbnail)
            b2 = Button(size_hint=(None, None), width=dp(50), height=dp(200), background_color=(1, 0, 0, 1))
            b.bind(on_press=lambda instance, button_id=self.BtnId: self.CamSelectButtonPressed(button_id))
    
            self.BtnId = self.BtnId + 1
            self.ids.CamSelectStackLayout.add_widget(b)
    
            b2.bind(on_press=lambda instance, button_id=self.DelBtnId: self.CamDeleteButtonPressed(button_id))
            self.DelBtnId = self.DelBtnId + 1
            self.ids.CamSelectStackLayout.add_widget(b2)
    

    Please add the threading and time imports at the beginning of your script so that they are imported before the MainScreen class definition.

    Now, when the app is running, the camera/IP buttons on the main screen will show thumbnail images of the streams. Note that this solution fetches the first frame as the thumbnail when creating the buttons, which might slow down the button-loading process for multiple streams.

  5. User

    thumnails work but they appear outside of buttons all in one place

  6. Assistant

    Apologies for the confusion. Instead of adding the thumbnail as a child widget of the button, we can create a custom button class that combines an Image and a Label for proper rendering. It will allow the thumbnail to be displayed within the button as a background and an address as text. Here's the updated code:

    from kivy.uix.label import Label
    
    class ImageButton(Button):
        def __init__(self, texture, address, **kwargs):
            super().__init__(**kwargs)
            self.thumbnail = Image(texture=texture, size=self.size, allow_stretch=True)
            self.address = Label(text=address, halign='center', valign='bottom')
            self.add_widget(self.thumbnail)
            self.add_widget(self.address)
    
        def on_size(self, *_):
            self.thumbnail.size = self.size
            self.address.size = self.size
    
    class MainScreen(Screen):
        # ... other code ...
    
        def CreateButtons(self, i):
            cap = cv2.VideoCapture(self.ServerListVar[i])
    
            # Capture the first frame as a thumbnail
            ret, frame = cap.read()
    
            if ret:
                buf = cv2.flip(frame, 0).tostring()
                texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='bgr')
                texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte')
            else:
                texture = Texture.create(size=(1, 1), colorfmt='bgr')
                buf = (128, 128, 128) * 3
                texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte')
    
            cap.release()
    
            # Create the button with the thumbnail as the background image
            b = ImageButton(
                texture=texture, 
                address=self.ServerListVar[i],
                size_hint=(None, None),
                width=dp(200),
                height=dp(200),
                background_normal=""
            )
            b2 = Button(size_hint=(None, None), width=dp(50), height=dp(200), background_color=(1, 0, 0, 1))
            b.bind(on_press=lambda instance, button_id=self.BtnId: self.CamSelectButtonPressed(button_id))
    
            self.BtnId = self.BtnId + 1
            self.ids.CamSelectStackLayout.add_widget(b)
    
            b2.bind(on_press=lambda instance, button_id=self.DelBtnId: self.CamDeleteButtonPressed(button_id))
            self.DelBtnId = self.DelBtnId + 1
            self.ids.CamSelectStackLayout.add_widget(b2)
    

    The code above defines a new class ImageButton that inherits from Button and adds an Image widget (self.thumbnail) and a Label widget (self.address) as child widgets. The ImageButton is initialized with a given texture for the thumbnail and the IP address as the label text.

    Finally, the CreateButtons() method is updated to create an ImageButton with the captured thumbnail texture. Now the buttons should display the thumbnail images as backgrounds with the IP addresses as text correctly.

  7. User

    TypeError: Properties ['address'] passed to init may not be existing property names. Valid properties are ['always_release', 'anchors', 'background_color', 'background_disabled_down', 'background_disabled_normal', 'background_down', 'background_normal', 'base_direction', 'bold', 'border', 'center', 'center_x', 'center_y', 'children', 'cls', 'color', 'disabled', 'disabled_color', 'disabled_image', 'disabled_outline_color', 'ellipsis_options', 'font_blended', 'font_context', 'font_family', 'font_features', 'font_hinting', 'font_kerning', 'font_name', 'font_size', 'halign', 'height', 'ids', 'is_shortened', 'italic', 'last_touch', 'line_height', 'markup', 'max_lines', 'min_state_time', 'mipmap', 'motion_filter', 'opacity', 'outline_color', 'outline_width', 'padding', 'padding_x', 'padding_y', 'parent', 'pos', 'pos_hint', 'refs', 'right', 'shorten', 'shorten_from', 'size', 'size_hint', 'size_hint_max', 'size_hint_max_x', 'size_hint_max_y', 'size_hint_min', 'size_hint_min_x', 'size_hint_min_y', 'size_hint_x', 'size_hint_y', 'split_str', 'state', 'state_image', 'strikethrough', 'strip', 'text', 'text_language', 'text_size', 'texture', 'texture_size', 'top', 'underline', 'unicode_errors', 'valign', 'width', 'x', 'y']

  8. Assistant

    Apologies for the oversight. I accidentally used an unregistered property ('address') in the ImageButton class. We can solve this issue by simply using the default 'text' property of the Button class.

    Here's the updated ImageButton class and how to use it in CreateButtons:

    class ImageButton(Button):
        def __init__(self, texture, **kwargs):
            super().__init__(text="", **kwargs)
            self.thumbnail = Image(texture=texture, size=self.size, allow_stretch=True, pos=self.pos)
            self.add_widget(self.thumbnail)
    
        def on_size(self, *_):
            self.thumbnail.size = self.size
            self.thumbnail.pos = self.pos
    
        def on_pos(self, *_):
            self.thumbnail.pos = self.pos
    
    class MainScreen(Screen):
        # ... other code ...
    
        def CreateButtons(self, i):
            cap = cv2.VideoCapture(self.ServerListVar[i])
    
            # Capture the first frame as a thumbnail
            ret, frame = cap.read()
    
            if ret:
                buf = cv2.flip(frame, 0).tostring()
                texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='bgr')
                texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte')
            else:
                texture = Texture.create(size=(1, 1), colorfmt='bgr')
                buf = (128, 128, 128) * 3
                texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte')
    
            cap.release()
    
            # Create the button with the thumbnail as the background image
            b = ImageButton(
                texture=texture,
                size_hint=(None, None),
                width=dp(200),
                height=dp(200),
                background_normal=""
            )
            b.text = self.ServerListVar[i]
    
            b2 = Button(size_hint=(None, None), width=dp(50), height=dp(200), background_color=(1, 0, 0, 1))
            b.bind(on_press=lambda instance, button_id=self.BtnId: self.CamSelectButtonPressed(button_id))
    
            self.BtnId = self.BtnId + 1
            self.ids.CamSelectStackLayout.add_widget(b)
    
            b2.bind(on_press=lambda instance, button_id=self.DelBtnId: self.CamDeleteButtonPressed(button_id))
            self.DelBtnId = self.DelBtnId + 1
            self.ids.CamSelectStackLayout.add_widget(b2)
    

    I have removed the 'address' property and used the default 'text' property of the Button class. Additionally, I added on_pos event to ImageButton to make sure the thumbnail's position is updated when the button's position changes. Now the buttons should display the thumbnail images with the IP addresses as text correctly.

  9. User

    def on_size(self, *): ^ SyntaxError: named arguments must follow bare *

  10. Assistant

    I apologize for the mistake. The correct syntax is to use *_ instead of *. Here is the updated ImageButton class with the corrected on_size and on_pos methods:

    class ImageButton(Button):
        def __init__(self, texture, **kwargs):
            super().__init__(text="", **kwargs)
            self.thumbnail = Image(texture=texture, size=self.size, allow_stretch=True, pos=self.pos)
            self.add_widget(self.thumbnail)
    
        def on_size(self, *_,):
            self.thumbnail.size = self.size
            self.thumbnail.pos = self.pos
    
        def on_pos(self, *_,):
            self.thumbnail.pos = self.pos
    

    The ImageButton class should now work without raising a syntax error.

  11. User

    File "e:\VS Code\IPCam\main.py", line 26, in on_size self.thumbnail.size = self.size AttributeError: 'ImageButton' object has no attribute 'thumbnail'

  12. Assistant

    I apologize for the confusion. It seems that the on_size and on_pos methods are called before __init__ completes, which results in the AttributeError. To fix this issue, we can use the @ syntax for binding the methods to the size and pos properties.

    Here is the updated ImageButton class with the corrected on_size and on_pos methods:

    class ImageButton(Button):
        def __init__(self, texture, **kwargs):
            super().__init__(text="", **kwargs)
            self.thumbnail = Image(texture=texture, size=self.size, allow_stretch=True, pos=self.pos)
            self.add_widget(self.thumbnail)
            self.bind(size=self.on_size, pos=self.on_pos)
    
        def on_size(self, instance, value):
            self.thumbnail.size = value
    
        def on_pos(self, instance, value):
            self.thumbnail.pos = value
    

    Now, the ImageButton class should work without raising the AttributeError. The thumbnail image in the ImageButton should now resize and reposition correctly.