H264 Codec
VideoWriter & H.264
Open CV's VideoWriter is used for saving image sequences into Video files. For Windows, the default Open CV implementation for saving MJPEG files do not provide much compression, if you are saving a long video file it may consume lost of hard drive space. H.264 video format generally provide great compression ratio with good image quality. One of the option to encode H.264 file using Open CV's VideoWriter, is to use the FFMPEG backend, and install Cisco's H.264 codec from here. While the cisco H.264 implementation using FFMpeg provides good default compression ratio, it is a require a separate download of the codec library from CISCO.
Here we are going to walk you through using the MSMF backend with VideoWriter, with which you can read and write video in H264 codec, without needing to download any extra codec from CISCO.
System Requirement
Component | Requirement | Detail |
---|---|---|
Emgu CV | Version 4.0+ | |
Operation System | Windows |
- The code used in this tutorial use components from the Open CV / Emgu CV 4.0 release.
Creating VideoWriter
To use the H264 codec, you will need to make sure your video file has the ".mp4" extension. e.g.
String fileName = String.Format("video_out.mp4");
The FOURCC code has to be 'H264'. e.g.
int fourcc = VideoWriter.Fourcc('H', '2', '6', '4');
When creating the VideoWriter, we need to use the "MSMF" backend. In Emgu CV v4.0, we have wrapped the Open CV functions that can be used to query the backend.
Backend[] backends = CvInvoke.WriterBackends;
int backend_idx = 0; //any backend;
foreach (Backend be in backends)
{
if (be.Name.Equals("MSMF"))
{
backend_idx = be.ID;
break;
}
}
//backend_idx should be the MSMF backend now
Now we can create our VideoWriter and write videos
using (VideoWriter vw = new VideoWriter(fileName, backend_idx, fourcc, 30, new Size(width, height), true))
{
// call vw.Write() to write frames to VideoWriter
}
Congratulations! Now you should have your H.264 video written out using MSMF.
You can review your video, get a feel of the quality, check the file size on the file.
Hope this helps!