用 OpenCVSharp 4.5 跑一遍 OpenCV官方教程
原官方教程链接:OpenCV: Creating a video with OpenCV
using System;
using OpenCvSharp;
namespace ConsoleApp1
{
class tutorial35 : ITutorial
{
public void Run()
{
string inputVideofile = @"I:\csharp\videos\Megamind.avi";
string outputVideofile = @"I:\csharp\videos\Megamind_output.avi";
int channel = 2; // Red Channel
VideoCapture inputVideo = new VideoCapture(inputVideofile);
if (!inputVideo.IsOpened())
{
Console.WriteLine("Could not open video file {0}", inputVideofile);
return;
}
//string::size_type pAt = source.find_last_of('.'); // Find extension point
//const string NAME = source.substr(0, pAt) + argv[2][0] + ".avi"; // Form the new name with container
int ex = (int)inputVideo.Get(VideoCaptureProperties.FourCC);// Get Codec Type- Int form
// Transform from int to char via Bitwise operators
char[] EXT = { (char)(ex & 0XFF), (char)((ex & 0XFF00) >> 8), (char)((ex & 0XFF0000) >> 16), (char)((ex & 0XFF000000) >> 24), (char)0 };
Size S = new Size((int)inputVideo.Get(VideoCaptureProperties.FrameWidth), // Acquire input size
(int)inputVideo.Get(VideoCaptureProperties.FrameHeight));
VideoWriter outputVideo = new VideoWriter(); // Open the output
outputVideo.Open(outputVideofile, ex, inputVideo.Get(VideoCaptureProperties.Fps), S, true);
if (!outputVideo.IsOpened())
{
Console.WriteLine("Could not open the output video for write: {0}", outputVideofile);
return;
}
Console.WriteLine("Input frame resolution: Width={0},Height={1}, of nr# {2}, Input Codec Type: {3}", S.Width, S.Height, inputVideo.Get(VideoCaptureProperties.FrameCount), EXT);
Mat src = new Mat(), res = new Mat();
Mat[] spl = new Mat[3];
for (; ; ) //Show the image captured in the window and repeat
{
inputVideo.Read(src); // read
if (src.Empty()) break; // check if at end
Cv2.Split(src, out spl); // process - extract only the correct channel
for (int i = 0; i < 3; ++i)
if (i != channel)
spl[i] = Mat.Zeros(S, spl[0].Type());
Cv2.Merge(spl, res);
//outputVideo.write(res); //save or
outputVideo.Write(res);
}
Console.WriteLine("Finished writing");
return;
}
}
}