Manitoba
Manitoba

Reputation: 8702

Picamera2 does not display correctly

I've bought an Arducam Eagle Eye 64Mpx camera to connect to my Raspberry Pi 5 (Bookworm). I've installed the required drivers and everything seems to be working using the libcamera-still command line.

I'd like to read the preview as a CV2 image to be loaded to a texture on my application. I also would like to add a capture button.

The following python code does work to display the preview (but AF does not seem to trigger so far):

import cv2
from picamera2 import Picamera2, Preview

picam2 = Picamera2(verbose_console=0)
picam2.configure(picam2.create_preview_configuration(main={'format': 'RGB888', 'size': (640, 480)}))
picam2.start_preview(Preview.NULL)
picam2.start()
picam2.set_controls({'AfMode': 1, 'AfTrigger': 1}) # Continuous autofocus

cv2.startWindowThread()
cv2.namedWindow('Camera', flags=cv2.WINDOW_GUI_NORMAL) # Mandatory to hide CV2 toolbar
while True:
    im = picam2.capture_array()
    cv2.imshow("Camera", im)
    cv2.waitKey(1)

cv2.destroyAllWindows()

I've also tried to mimic a streaming event to read the image but it can only display a small black picture (even with the buttons...):

import io
import cv2
import time
import numpy as np
from threading import Condition
from picamera2 import Picamera2, Preview
from picamera2.encoders import MJPEGEncoder
from picamera2.outputs import FileOutput

class StreamingOutput(io.BufferedIOBase):
    def __init__(self):
        self.frame = None
        self.condition = Condition()

    def write(self, buf):
        with self.condition:
            nparr = np.frombuffer(buf, np.uint8)
            self.frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
            self.condition.notify_all()

picam2 = Picamera2(verbose_console=0)
picam2.configure(picam2.create_video_configuration(main={'format': 'RGB888', 'size': (640, 480)}))
output = StreamingOutput()
picam2.start_recording(MJPEGEncoder(), FileOutput(output))
picam2.streaming_output = output

cv2.startWindowThread()
cv2.namedWindow("Camera", cv2.WINDOW_NORMAL)
while True:
    with picam2.streaming_output.condition:
        picam2.streaming_output.condition.wait()
        im = picam2.streaming_output.frame
    print(im.shape)
    cv2.imshow("Camera", im)

In this example, im.shape equals (480, 640, 3) which seems correct but cv2.imshow only display a small black picture.

Is there something I don't understand with picamera2 ?

Upvotes: 0

Views: 291

Answers (0)

Related Questions