请写一个函数,另一个程序调用realsense相机进行拍照,并保存

import pyrealsense2 as rs
import cv2
import os

def take_photo(file_dir):
    # 定义相机分辨率和帧速
    width, height = 640, 480
    fps = 30

    # 配置相机
    pipe = rs.pipeline()
    config = rs.config()
    config.enable_stream(rs.stream.color, width, height, rs.format.bgr8, fps)
    config.enable_stream(rs.stream.depth, width, height, rs.format.z16, fps)

    # 启动相机
    pipe.start(config)

     # 获取相机实例
    profile = pipe.get_active_profile()
    color_stream = profile.get_stream(rs.stream.color)
    depth_stream = profile.get_stream(rs.stream.depth)

    # 获取相机数据
    frames = pipe.wait_for_frames()

    # 获取彩色图像
    color_frame = frames.get_color_frame()
    color_image = None
    if color_frame:
        color_image = np.asanyarray(color_frame.get_data())
        cv2.imshow('Color Stream', color_image)
        
    # 关闭相机
    pipe.stop()
    cv2.destroyAllWindows()

    # 将图像保存到文件
    if color_image is not None:
        file_path = os.path.join(file_dir, 'photo.jpg')
        cv2.imwrite(file_path, color_image)
        print('Photo saved to:', file_path)
    else:
        print('Failed to capture photo')

该函数接受一个参数 file_dir,表示图片要保存的目录,调用该函数可以创建一个相机实例,拍摄一张彩色图像,并将图像保存到指定目录下的photo.jpg文件中。下面是一个使用该函数的例子:

save_dir = '/path/to/save'
take_photo(save_dir)

注意替换 /path/to/save 为你想要保存到的目录。

你可能感兴趣的:(数码相机)