Jetson Nano使用notebook实时显示CSI摄像头画面
Jetson nano 在使用CSI摄像头时,使用方法与Raspberry Pi有点出入
凌顺实验室(lingshunlab.com)分享的以下jutpterlab-notebook代码,实测可以实时显示摄像头画面在notebook上。
把一下代码复制到notebook上并运行:
# 查看摄像头信息
!v4l2-ctl -d 0 -l
# gstreamer信息生成
def gstreamer_pipeline(
sensor_id=0,
capture_width=1920,
capture_height=1080,
display_width=960,
display_height=540,
framerate=30,
flip_method=0,
):
return (
"nvarguscamerasrc sensor-id=%d ! "
"video/x-raw(memory:NVMM), width=(int)%d, height=(int)%d, framerate=(fraction)%d/1 ! "
"nvvidconv flip-method=%d ! "
"video/x-raw, width=(int)%d, height=(int)%d, format=(string)BGRx ! "
"videoconvert ! "
"video/x-raw, format=(string)BGR ! appsink"
% (
sensor_id,
capture_width,
capture_height,
framerate,
flip_method,
display_width,
display_height,
)
)
# 数据转换
def bgr8_to_jpeg(value, quality=10):
return bytes(cv2.imencode('.jpg', value)[1])
class Camera(SingletonConfigurable):
value = traitlets.Any()
def __init__(self):
try:
self.cap = cv2.VideoCapture(gstreamer_pipeline(flip_method=0), cv2.CAP_GSTREAMER)
re, image = self.cap.read()
if not re:
raise RuntimeError('Could not read image from camera.')
self.value = image
self.start()
except:
self.stop()
raise RuntimeError(
'Could not initialize camera. Please see error trace.')
atexit.register(self.stop)
def _capture_frames(self):
while True:
re, image = self.cap.read()
if re:
self.value = image
else:
break
def start(self):
# if not self.cap.isOpened():
# self.cap.open(self._gst_str(), cv2.CAP_GSTREAMER)
if not hasattr(self, 'thread') or not self.thread.isAlive():
self.thread = threading.Thread(target=self._capture_frames)
self.thread.start()
def stop(self):
if hasattr(self, 'cap'):
self.cap.release()
if hasattr(self, 'thread'):
self.thread.join()
# 把摄像头画面显示在notebook上
image = widgets.Image(format='jpeg', width=500, height=500) # this width and height doesn't necessarily have to match the camera
camera = Camera()
traitlets.dlink((camera, 'value'), (image, 'value'), transform=bgr8_to_jpeg)
display(image)
# 关闭摄像头
camera.stop()