效果
项目
代码
using OpenCvSharp;
using OpenCvSharp.Extensions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;namespace OpenCvSharp_读取rtsp流
{public partial class Form1 : Form{public Form1(){InitializeComponent();}CancellationTokenSource cts;VideoCapture capture;private void button1_Click(object sender, EventArgs e){if (textBoxIP.Text == "" || textBoxPort.Text == "" ||textBoxUserName.Text == "" || textBoxPassword.Text == ""){MessageBox.Show("Please input IP, Port, User name and Password!");return;}String rtspUrl = string.Format("rtsp://{0}:{1}@{2}:{3}", textBoxUserName.Text, textBoxPassword.Text, textBoxIP.Text, textBoxPort.Text);button1.Enabled = false;button2.Enabled = true;cts = new CancellationTokenSource();Task task = new Task(() =>{capture.Open(rtspUrl, VideoCaptureAPIs.ANY);if (capture.IsOpened()){//var dsize = new System.Windows.Size(capture.FrameWidth, capture.FrameHeight);Mat frame = new Mat();while (true){Thread.Sleep(10);//判断是否被取消;if (cts.Token.IsCancellationRequested){pictureBox1.Image = null;return;}//Read imagecapture.Read(frame);if (frame.Empty())continue;if (pictureBox1.Image != null){pictureBox1.Image.Dispose();}pictureBox1.Image = BitmapConverter.ToBitmap(frame);}}}, cts.Token);task.Start();}private void Form1_Load(object sender, EventArgs e){capture = new VideoCapture();}private void button2_Click(object sender, EventArgs e){button2.Enabled = false;button1.Enabled = true;cts.Cancel();}private void Form1_FormClosing(object sender, FormClosingEventArgs e){if (capture != null){capture.Release();capture.Dispose();}}}
}
Demo下载