raw12 to rgb conversion using v4l2

75 Views Asked by At

I am using Leopard Imaging OX03F camera through their USB inteface board. This camera outputs RAW12 data encapsulated in YUYV format. Each pixel is 12-bit data using two bytes (high 4 bits are 0, and low 12 bits are RAW). Since UVC standard has no RAW image format, it uses YUYV as the wrapper.

I am trying the python based v4l2 program but i am getting bad address error: fcntl.ioctl(video_device, v4l2.VIDIOC_STREAMON, v4l2.V4L2_BUF_TYPE_VIDEO_CAPTURE) OSError: [Errno 14] Bad address

can someone help ?

import v4l2
import fcntl
import mmap
import numpy as np
import cv2

# Open the video device
video_device = open('/dev/video2', 'rb+', buffering=0)

# Set the format to YUYV
fmt = v4l2.v4l2_format()
fmt.type = v4l2.V4L2_BUF_TYPE_VIDEO_CAPTURE
fmt.fmt.pix.width = 1920
fmt.fmt.pix.height = 1542
fmt.fmt.pix.pixelformat = v4l2.V4L2_PIX_FMT_YUYV
fcntl.ioctl(video_device, v4l2.VIDIOC_S_FMT, fmt)

# Request a frame
req = v4l2.v4l2_requestbuffers(5)
req.type = v4l2.V4L2_BUF_TYPE_VIDEO_CAPTURE
req.memory = v4l2.V4L2_MEMORY_MMAP
req.count = 5  
#https://forums.raspberrypi.com/viewtopic.php?t=195934  -- does not resolve the issue still
fcntl.ioctl(video_device, v4l2.VIDIOC_REQBUFS, req)

# Set up buffer and memory mapping
buf = v4l2.v4l2_buffer()
buf.type = v4l2.V4L2_BUF_TYPE_VIDEO_CAPTURE
buf.memory = v4l2.V4L2_MEMORY_MMAP
buf.index = 0

# Request and map the buffer
fcntl.ioctl(video_device, v4l2.VIDIOC_QUERYBUF, buf)
#frame = mmap.mmap(video_device.fileno(), buf.length, offset=buf.m.offset)
frame = mmap.mmap(video_device.fileno(), buf.length, mmap.MAP_SHARED, mmap.PROT_READ | mmap.PROT_WRITE, offset=buf.m.offset)

# Read a frame
fcntl.ioctl(video_device, v4l2.VIDIOC_QBUF, buf)
fcntl.ioctl(video_device, v4l2.VIDIOC_STREAMON, v4l2.V4L2_BUF_TYPE_VIDEO_CAPTURE)
#https://forums.developer.nvidia.com/t/12-bits-images-from-argus-camera/264491/15 ---- same issue
fcntl.ioctl(video_device, v4l2.VIDIOC_DQBUF, buf)
frame_data = np.frombuffer(frame, dtype=np.uint8)

# Unwrap YUYV to a grayscale image
yuyv_image = frame_data.reshape(1542, 1920, 2)
y_image = yuyv_image[:, :, 0]

# Perform YUV to BGR conversion
bgr_image = cv2.cvtColor(cv2.cvtColor(y_image, cv2.COLOR_YUV2BGR_YUYV), cv2.COLOR_BGR2RGB)

# Display or process the BGR image
cv2.imshow('YUYV to BGR', bgr_image)
cv2.waitKey(0)

# Cleanup
fcntl.ioctl(video_device, v4l2.VIDIOC_STREAMOFF, v4l2.V4L2_BUF_TYPE_VIDEO_CAPTURE)
video_device.close()
0

There are 0 best solutions below