public class VideoReceivedEventArgs : EventArgs
{
public Mat Frame { get; set; }
public VideoReceivedEventArgs(Mat frame)
{
this.Frame = frame;
}
}
internal interface IVideoReceiver : IDisposable
{
string Camera { get; }
bool IsConnected { get; }
double Fps { get; }
Size Size { get; }
event EventHandler<VideoReceivedEventArgs> VideoReceived;
bool Connect();
bool Disconnect();
Mat Receive();
}
internal class VideoReceiver : IVideoReceiver
{
public bool IsConnected => this.capture?.IsOpened() ?? false;
public double Fps { get; private set; }
public Size Size { get; private set; }
public string Camera { get; private set; }
private string url;
public VideoReceiver(string camera, string url)
{
this.Camera = camera;
this.url = url;
}
private VideoCapture capture;
public bool Connect()
{
this.Disconnect();
this.capture = new VideoCapture(url)
{
BufferSize = 256
};
this.capture.Set(VideoCaptureProperties.PosMsec, 0);
this.capture.Set(VideoCaptureProperties.PosFrames, 0);
this.capture.Set(VideoCaptureProperties.Fps, 15);
this.capture.Open(url);
this.Size = new Size(this.capture.FrameWidth, this.capture.FrameHeight);
this.Fps = this.capture.Fps;
return this.IsConnected;
}
public event EventHandler<VideoReceivedEventArgs> VideoReceived;
protected virtual void OnVideoReceived(VideoReceivedEventArgs e)
{
this.VideoReceived?.Invoke(this, e);
}
public bool Disconnect()
{
this.capture?.Release();
this.capture?.Dispose();
this.capture = null;
return true;
}
public Mat Receive()
{
if (this.capture is null)
{
return null;
}
var frame = new Mat();
this.capture.Read(frame);
this.OnVideoReceived(new VideoReceivedEventArgs(frame));
return frame;
}
public void Dispose()
{
this.Dispose(disposing: true);
GC.SuppressFinalize(this);
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
capture.Dispose();
}
this.capture = null;
disposed = true;
}
}
}
C# OpenCV 接收RSTP视频流
于 2024-06-17 11:37:39 首次发布