C#使用OpenCvSharp4實現(xiàn)讀取本地視頻
OpenCvSharp4庫
OpenCvSharp4庫是一個基于.Net封裝的OpenCV庫,Github源代碼地址為:https://github.com/shimat/opencvsharp,里面有關于Windows下安裝OpenCvSharp4庫的描述,如下圖所示:

視頻資源地址
視頻資源可以到https://github.com/murtazahassan/Learn-OpenCV-in-3-hours/blob/master/Resources/test_video.mp4下載
新建一個C# .Net控制臺程序OpenCVExample,并安裝OpenCvSharp4和OpenCvSharp4.runtime.win兩個NuGet包,或者直接安裝OpenCvSharp4.Windows

C#示例代碼
C#示例代碼如下,如下代碼展示了怎么使用VideoCapture和Cv2.ImShow讀取本地視頻:
using OpenCvSharp;
using System;
namespace OpenCVExample
{
public class Program
{
/// <summary>
/// 讀取本地視頻并逐幀顯示
/// </summary>
public static void ReadLocalVideo()
{
VideoCapture cap = new VideoCapture("Resources\\test_video.mp4"); // 讀取本地視頻文件
if (!cap.IsOpened())
{
Console.WriteLine("VidepCapture open failed");
return;
}
while (true)
{ // 如果cap初始化成功
Mat frame = new Mat();
if (cap.Read(frame)) // 抓取和解碼,返回下一幀
{
Cv2.ImShow("video Result", frame);
if (Cv2.WaitKey(1) == (int)('q')) // 用戶輸入q鍵退出
{
break;
}
}
else
{
// 當視頻播放完畢,也退出
Console.WriteLine("there is no frame to read");
break;
}
}
}
static void Main(string[] args)
{
ReadLocalVideo();
//Console.ReadKey();
}
}
}
運行結果
程序運行結果如下圖所示:

到此這篇關于C#使用OpenCvSharp4實現(xiàn)讀取本地視頻的文章就介紹到這了,更多相關C# OpenCvSharp4讀取視頻內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

