Как сохранить изображения Intel Realsense в списке (pyrealsense2)

Я пытаюсь сохранить как глубину, так и цветные изображения камеры Intel Realsense D435i в списке из 300 изображений. Затем я буду использовать многопроцессорную обработку, чтобы сохранить этот фрагмент из 300 изображений на свой диск. Но каждый раз, когда я пытаюсь, программа успешно добавляет 15 изображений в список, а затем я получаю эту ошибку:

    Frame didn't arrived within 5000

Я убедился, что у меня установлена ​​64-битная версия на python 3.6, и камера работает отлично, когда я не пытаюсь сохранить изображения в списке. Зритель в реальном смысле тоже отлично работает. Я также пробовал с разными разрешениями и частотой кадров, но, похоже, это тоже не работает. Что интересно, если я сохраню только цветные изображения, я не получу ту же ошибку, вместо этого я снова и снова буду получать одно и то же цветное изображение в списке.

if __name__ == '__main__':
pipeline = rs.pipeline()
config = rs.config()

config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
config.enable_stream(rs.stream.color, 1280, 720, rs.format.bgr8, 30)
profile = pipeline.start(config)

depth_sensor = profile.get_device().first_depth_sensor()
depth_sensor.set_option(
    rs.option.visual_preset, 3
)  # Set high accuracy for depth sensor
depth_scale = depth_sensor.get_depth_scale()

align_to = rs.stream.color
align = rs.align(align_to)

#   Init variables
im_count = 0
image_chunk = []
image_chunk2 = []
# sentinel = True
try:
    while True:

        # Wait for a coherent pair of frames: depth and color
        frames = pipeline.wait_for_frames()
        aligned_frames = align.process(frames)
        aligned_depth_frame = aligned_frames.get_depth_frame()
        color_frame = aligned_frames.get_color_frame()


        if not aligned_depth_frame or not color_frame:
            print("problem here")
            raise RuntimeError("Could not acquire depth or color frames.")

        depth_image = np.asanyarray(aligned_depth_frame.get_data())
        color_image = np.asanyarray(color_frame.get_data())

        image_chunk.append(color_image)
        image_chunk2.append(depth_image)




except Exception as e:
    print(e)

finally:
    # Stop streaming
    pipeline.stop()

Мне просто нужно сохранить 300 изображений подряд, вот и все, поэтому я очень обеспокоен тем, что вызывает эту проблему.


person Andrew Jouffray    schedule 18.08.2019    source источник
comment
Каким-то образом .append() вызывает RuntimeError. Я также испытываю подобную проблему.   -  person Physicing    schedule 22.10.2019
comment
Я рад узнать, что я не единственный, альтернатива - сохранить поток в файлы .bag.   -  person Andrew Jouffray    schedule 15.11.2019
comment
Я столкнулся с аналогичной проблемой здесь stackoverflow.com/q/63027477/2478346   -  person CATALUNA84    schedule 22.07.2020
comment
Вы не можете помещать кадры в список, так как это блокирует память. Массив numpy, созданный из фрейма, по-прежнему указывает на память фрейма. Вы должны скопировать (т.е. клонировать) его, чтобы сломать ссылку. В конце концов у вас закончится память, если вы каким-либо образом храните дескрипторы кадров (буферная память USB, а не память ПК).   -  person VoteCoffee    schedule 08.02.2021


Ответы (1)


Удержание кадра блокирует память, и в конечном итоге она достигает предела, что не позволяет получить больше изображений. Несмотря на то, что вы создаете изображение, данные по-прежнему находятся в кадре. Вам необходимо клонировать изображение после его создания, чтобы освободить ссылку на память фрейма.

depth_image = np.asanyarray(aligned_depth_frame.get_data())
color_image = np.asanyarray(color_frame.get_data())

depth_image = depth_image.copy()
color_image = color_image.copy()

image_chunk.append(color_image)
image_chunk2.append(depth_image)

Подробнее о фреймах и управлении памятью читайте здесь: https://dev.intelrealsense.com/docs/frame-management

Я создал класс-оболочку для извлечения различных элементов из набора фреймов, которые нельзя воссоздать позже. Это немного тяжело, но показывает некоторые общие операции, которые могут быть полезны для других:

colorizer = None
align_to_depth = None
align_to_color = None
pointcloud = rs.pointcloud()

class IntelD435ImagePacket:
    """
    Class that contains image and associated processing data.
    """

    @property
    def frame_id(self):
        return self._frame_id

    @property
    def timestamp(self):
        return self._timestamp

    @property
    def image_color(self):
        return self._image_color

    @property
    def image_depth(self):
        return self._image_depth

    @property
    def image_color_aligned(self):
        return self._image_color_aligned

    @property
    def image_depth_aligned(self):
        return self._image_depth_aligned

    @property
    def image_depth_colorized(self):
        if not self._image_depth_colorized:
            self._image_depth_colorized = cv2.applyColorMap(self.image_depth, cv2.COLORMAP_JET);
        return self._image_depth_colorized

    @property
    def intrinsics(self):
        return self._intrinsics

    @property
    def pointcloud(self):
        return self._pointcloud

    @property
    def pointcloud_texture(self):
        return self._pointcloud_texture

    def _rs_intrinsics_to_opencv_matrix(self, rs_intrinsics):
        fx = rs_intrinsics.fx
        fy = rs_intrinsics.fy
        cx = rs_intrinsics.ppx
        cy = rs_intrinsics.ppy
        s = 0  # skew
        return np.array([fx, s, cx,
                         0, fy, cy,
                         0, 0, 1]).reshape(3, 3)

    def __init__(self, frame_set, frame_id=None, timestamp=None, *args, **kwargs):
        global colorizer
        if not colorizer:
            colorizer = rs.colorizer()
            colorizer.set_option(rs.option.color_scheme, 0)

        global align_to_depth
        if not align_to_depth:
            align_to_depth = rs.align(rs.stream.depth)

        global align_to_color
        if not align_to_color:
            align_to_color = rs.align(rs.stream.color)

        global pointcloud
        if not pointcloud:
             pointcloud = rs.pointcloud()

        # Get intrinsics
        profile = frame_set.get_profile()
        video_stream_profile = profile.as_video_stream_profile()
        rs_intrinsics = video_stream_profile.get_intrinsics()
        self._intrinsics = self._rs_intrinsics_to_opencv_matrix(rs_intrinsics)

        # Get pointcloud
        depth_frame = frame_set.get_depth_frame()
        color_frame = frame_set.get_color_frame()
        pointcloud.map_to(color_frame)
        points = pointcloud.calculate(depth_frame)
        vtx = np.asanyarray(points.get_vertices())
        points_arr = vtx.view(np.float32).reshape(vtx.shape + (-1,)).copy()
        self._pointcloud = points_arr

        # Get pointcloud texture mapping
        tex = np.asanyarray(points.get_texture_coordinates())
        color_map_arr = tex.view(np.float32).reshape(tex.shape + (-1,)).copy()
        self._pointcloud_texture = color_map_arr

        # Extract color image
        color_frame = frame_set.get_color_frame()
        self._image_color = np.asanyarray(color_frame.get_data()).copy()

        # Extract depth image
        depth_frame = frame_set.get_depth_frame()
        self._image_depth = np.asanyarray(depth_frame.get_data()).copy()

        # Align the color frame to depth frame and extract color image
        color_frame_aligned = align_to_depth.process(frame_set).get_color_frame()
        self._image_color_aligned = np.asanyarray(color_frame_aligned.get_data()).copy()

        # Align the depth frame to color frame and extract depth image
        depth_frame_aligned = align_to_color.process(frame_set).get_depth_frame()
        self._image_depth_aligned = np.asanyarray(depth_frame_aligned.get_data()).copy()

        self._image_depth_colorized = None
        if frame_id:
            self._frame_id = frame_id
        else:
            self._frame_id = frame_set.frame_number
        if timestamp:
            self._timestamp = timestamp
        else:
            self._timestamp = frame_set.timestamp
        self.__dict__.update(kwargs)
person VoteCoffee    schedule 08.02.2021