I am trying to write real-time images into video file acquired by Kinect in Ubuntu. See below the sample code:
#!/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()
The code works smoothly and doesn't show any error in terminal. However, it doesn't produce any video file, even when I terminate it using ctrl+c
.
Use a codec for saving your video. Motion Jpeg almost always works!
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
self.video_writer = cv2.VideoWriter(file_name, fourcc, fps, frame_size)
then the rest of the story.