Python 中无法使用 OpenCV 编写视频

Unable to write video using OpenCV in Python

我正在尝试将实时图像写入 Ubuntu 中通过 Kinect 获取的视频文件。请参阅下面的示例代码:

#!/usr/bin/env python
import roslib
roslib.load_manifest('ros_package_name')
import rospy
import cv2
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError

class image_converter(object):
    def __init__(self, topic_name, file_name, fps=20):
        self.fps = fps
        self.file_name = file_name
        self.bridge = CvBridge()
        self.image_sub = rospy.Subscriber(topic_name, Image, self.callback)
        self.video_writer = None

    def callback(self,data):
        try:
            cv_image = self.bridge.imgmsg_to_cv2(data, 'bgr8')
        except CvBridgeError as e:
            print e

        if self.video_writer is None:
            rows, cols, _ = cv_image.shape
            self.video_writer = cv2.VideoWriter(self.file_name, -1, self.fps, (cols, rows))

        self.video_writer.write(cv_image)

    def clean_shutdown(self):
        if self.video_writer is not None:
            self.video_writer.release()
        print 'Saving video file', self.file_name

    def __del__(self):
        self.clean_shutdown()

def main():
    ic = image_converter('/kinect2/qhd/image_color_rect','video.avi')
    rospy.init_node('save_video', anonymous=True)
    rospy.on_shutdown(ic.clean_shutdown)
    rospy.spin()

代码运行流畅,终端中未显示任何错误。但是,它不会生成任何视频文件,即使我使用 ctrl+c.

终止它也是如此

使用编解码器保存您的视频。 Motion Jpeg 几乎总是有效!

fourcc = cv2.VideoWriter_fourcc(*'MJPG')
self.video_writer = cv2.VideoWriter(file_name, fourcc, fps, frame_size)

然后是故事的其余部分。