Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 3838

Troubleshooting • Failed to allocate required memory

$
0
0
Hello Forum

I am new to forum as well as to PI. I am using Pi-5 to develop GUI with two camera interface below is my code and error. I am unable to find solution. Memory allocation 1024MB

Code:

Initializing camera 0...[ WARN:0@1.511] global ./modules/videoio/src/cap_gstreamer.cpp (2401) handleMessage OpenCV | GStreamer warning: Embedded video playback halted; module v4l2src0 reported: Failed to allocate required memory.[ WARN:0@1.511] global ./modules/videoio/src/cap_gstreamer.cpp (1356) open OpenCV | GStreamer warning: unable to start pipeline[ WARN:0@1.511] global ./modules/videoio/src/cap_gstreamer.cpp (862) isPipelinePlaying OpenCV | GStreamer warning: GStreamer: pipeline have not been createdCamera 0 initializedFront camera initializedInitializing camera 2...[ WARN:0@1.529] global ./modules/videoio/src/cap_gstreamer.cpp (2401) handleMessage OpenCV | GStreamer warning: Embedded video playback halted; module v4l2src1 reported: Failed to allocate required memory.[ WARN:0@1.529] global ./modules/videoio/src/cap_gstreamer.cpp (1356) open OpenCV | GStreamer warning: unable to start pipeline[ WARN:0@1.529] global ./modules/videoio/src/cap_gstreamer.cpp (862) isPipelinePlaying OpenCV | GStreamer warning: GStreamer: pipeline have not been createdCamera 2 initializedRear camera initializedWARNING: running xinput against an Xwayland server. See the xinput man page for details.[import cv2from kivy.app import Appfrom kivy.uix.floatlayout import FloatLayoutfrom kivy.uix.slider import Sliderfrom kivy.uix.label import Labelfrom kivy.uix.image import Imagefrom kivy.core.window import Windowfrom kivy.uix.button import Buttonfrom kivy.uix.boxlayout import BoxLayoutfrom kivy.graphics.texture import Textureimport timeimport RPi.GPIO as GPIOWindow.size = (1024, 600)  # Set screen resolution# Set up the GPIO pin for PWM and Auto/Manual button (example pin)LED_PIN = 18AUTO_MANUAL_PIN = 17FWD_REV_PIN = 16ARM_ON_OFF_PIN = 15GPIO.setmode(GPIO.BCM)GPIO.setup(LED_PIN, GPIO.OUT)GPIO.setup(AUTO_MANUAL_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)GPIO.setup(FWD_REV_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)GPIO.setup(ARM_ON_OFF_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)pwm = GPIO.PWM(LED_PIN, 1000)  # Set up PWM with 1000Hz frequencypwm.start(0)  # Start with the LED offdef initialize_camera(camera_index):    retries = 3    while retries > 0:        try:            print(f"Initializing camera {camera_index}...")            camera = cv2.VideoCapture(camera_index)            if not camera.isOpened():                raise RuntimeError(f"Failed to open camera with index {camera_index}")            camera.set(cv2.CAP_PROP_FRAME_WIDTH, 640)            camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)            print(f"Camera {camera_index} initialized")            return camera        except RuntimeError as e:            print(f"Error initializing camera: {e}")            retries -= 1            print(f"Retrying... {retries} attempts left")            time.sleep(2)    raise RuntimeError(f"Failed to initialize the camera {camera_index} after multiple attempts")class CameraFrame(FloatLayout):    def __init__(self, camera=None, **kwargs):        super().__init__(**kwargs)        self.size_hint = (1, 1)        self.image = Image(source='', size_hint=(1, 1), pos_hint={'x': 0, 'y': 0}, allow_stretch=True, keep_ratio=True)        self.add_widget(self.image)                self.camera = camera        if camera:            self.update_camera_feed()        else:            self.add_no_camera_label("No camera detected")                self.create_slider_and_labels()        self.create_buttons()    def add_no_camera_label(self, label_text):        no_camera_label = Label(text=label_text, size_hint=(1, 1), halign='center', valign='middle')        self.add_widget(no_camera_label)    def update_camera_feed(self):        if self.camera:            ret, frame = self.camera.read()            if ret:                frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)                if not self.image.texture or self.image.texture.size != (frame.shape[1], frame.shape[0]):                    self.image.texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='rgb')                    self.image.texture.flip_vertical()                self.image.texture.blit_buffer(frame_rgb.tobytes(), colorfmt='rgb', bufferfmt='ubyte')                self.image.canvas.ask_update()            else:                self.add_no_camera_label("Error reading from camera")    def create_slider_and_labels(self):        slider = Slider(min=0, max=100, value=50, orientation='vertical', size_hint=(None, 0.9), width=50)        slider.bind(value=self.update_label_and_pwm)        slider.pos_hint = {'x': 0.9, 'y': 0.05}        self.add_widget(slider)        label = Label(text="FL", size_hint=(None, None), size=(50, 30), pos_hint={'x': 0.9, 'y': 0.94})        self.add_widget(label)        self.percentage_label = Label(text="50%", size_hint=(None, None), size=(50, 30), pos_hint={'x': 0.9, 'y': 0.0})        self.add_widget(self.percentage_label)    def update_label_and_pwm(self, slider, value):        self.percentage_label.text = f"{int(value)}%"        pwm.ChangeDutyCycle(value)    def create_buttons(self):        fc_button = Button(text="Front Camera", size_hint=(None, None), size=(113, 56.5), pos_hint={'x': 0.0, 'y': 0.9})        fc_button.bind(on_press=self.on_button_press)        self.add_widget(fc_button)        rc_button = Button(text="Rear Camera", size_hint=(None, None), size=(113, 56.5), pos_hint={'x': 0.0, 'y': 0.78})        rc_button.bind(on_press=self.on_button_press)        self.add_widget(rc_button)        fr_button = Button(text="Both Camera", size_hint=(None, None), size=(113, 56.5), pos_hint={'x': 0.0, 'y': 0.66})        fr_button.bind(on_press=self.on_button_press)        self.add_widget(fr_button)    def on_button_press(self, instance):        if hasattr(self, 'highlighted_button') and self.highlighted_button:            self.highlighted_button.background_color = (1, 1, 1, 1)        instance.background_color = (0.5, 0.5, 1, 1)        self.highlighted_button = instanceclass DualCameraApp(App):    def build(self):        layout = BoxLayout(orientation='vertical')                # Initialize the front and rear cameras using indices        try:            front_camera = initialize_camera(0) # Front camera at index 0            print("Front camera initialized")            rear_camera = initialize_camera(2)   # Rear camera at index 1            print("Rear camera initialized")        except RuntimeError as e:            print(f"Camera initialization failed: {e}")            front_camera = None            rear_camera = None        # Check for available cameras and add frames accordingly        frame1 = CameraFrame(camera=front_camera)  # Default to front camera        layout.add_widget(frame1)        # Logic to switch between front, rear, and both cameras        def update_camera_feed(instance):            if instance.text == "Front Camera":                frame1.camera = front_camera            elif instance.text == "Rear Camera":                frame1.camera = rear_camera            layout.clear_widgets()            layout.add_widget(frame1)        # Add buttons to switch cameras        fc_button = Button(text="Front Camera", size_hint=(None, None), size=(113, 56.5), pos_hint={'x': 0.0, 'y': 0.9})        fc_button.bind(on_press=update_camera_feed)        layout.add_widget(fc_button)        rc_button = Button(text="Rear Camera", size_hint=(None, None), size=(113, 56.5), pos_hint={'x': 0.0, 'y': 0.78})        rc_button.bind(on_press=update_camera_feed)        layout.add_widget(rc_button)        fr_button = Button(text="Both Camera", size_hint=(None, None), size=(113, 56.5), pos_hint={'x': 0.0, 'y': 0.66})        fr_button.bind(on_press=update_camera_feed)        layout.add_widget(fr_button)        return layout            def on_stop(self):        if hasattr(self, 'front_camera') and self.front_camera and self.front_camera.isOpened():            self.front_camera.release()        if hasattr(self, 'rear_camera') and self.rear_camera and self.rear_camera.isOpened():            self.rear_camera.release()        pwm.stop()        GPIO.cleanup()if __name__ == '__main__':    try:        DualCameraApp().run()    finally:        # Clean up GPIO and stop PWM when the app is closed        pwm.stop()        GPIO.cleanup()]

Statistics: Posted by PankajHarsh — Fri Nov 15, 2024 1:42 pm



Viewing all articles
Browse latest Browse all 3838

Trending Articles