For video monitoring users, writing video files is almost a required step. Here, I will give an example of video file writing. First, use opencv to capture the video from a USB camera, and then write the video frame into the video file. Before writing a video file, there are two reminders:
(1) opencv is only a tool library for image processing. It is not a tool library for video processing! That is to say, the object it processes should be an image, while opencv itself has some API functions that can be read by a USB camera, however, it only calls the underlying VFW module of windows. Therefore, if you are an operating system such as Windows Vista or Windows 7, Microsoft may have abandoned the VFW module. At this time, the video frame cannot be obtained by using the camera video capture function of opencv.
For reading and writing (2)video file (.mpeg,.mp4,. rmvb,. Avi, etc.), a special video codecs are required. Obviously, different video formats use different video encoding technologies (it is worth noting that ,. AVI format video files, although the suffix is the same, but the internal use of the video encoding algorithm may still be different, specific can refer to here http://blog.csdn.net/carson2005/article/details/6314089), so, before reading and writing video files, you need to follow the corresponding video codecs. Storm, kmplayer and other video players already include the codecs of commonly used video format files. Therefore, you can directly use them to play video files.
OK. After learning about the above two points, you will know that you must download the corresponding video codecs before using opencv to write video files. Commonly used DivX, Xvid, FFMPEG and so on, the author here using Xvid (here there is a brief introduction: http://blog.csdn.net/carson2005/article/details/6553867 ).
The following is a reference code:
# Include "stdafx. H"
# Include "cv. H"
# Include "highgui. H"
# Include "iostream"
Using namespace STD;
Int _ tmain (INT argc, _ tchar * argv [])
{
Cvcapture * Cap = cvcreatecameracapture (0); // initialize the pointer captured by the camera
If (! CAP)
{
Cout <"create camera capture error..." <Endl;
System ("pause ");
Exit (-1 );
}
Iplimage * tempimg = cvqueryframe (CAP );
Double FPS = 20;
Cvsize size = cvsize (
(INT) cvgetcaptureproperty (Cap, cv_cap_prop_frame_width ),
(INT) cvgetcaptureproperty (Cap, cv_cap_prop_frame_height)
);
Cvvideowriter * Writer = cvcreatevideowriter ("C:/test. Avi", cv_fourcc ('x', 'V', 'I', 'D'), FPS, size );
Iplimage * IMG = cvcreateimage (size, 8, 3 );
While (tempimg = cvqueryframe (CAP ))! = NULL)
{
Cvcopy (tempimg, IMG );
If (IMG-> origin = ipl_origin_tl)
{
Cvflip (IMG, IMG );
}
Cvwriteframe (writer, IMG );
}
Cvreleaseimage (& IMG );
Cvreleasecapture (& Cap );
Cvreleasevideowriter (& writer );
System ("pause ");
Return 0;
}