76 lines
2.0 KiB
C#
76 lines
2.0 KiB
C#
using OpenCvSharp;
|
|
using System.Threading;
|
|
|
|
namespace AIParkingApplication
|
|
{
|
|
public delegate void CameraEvent(Mat videoFrame);
|
|
public class Camera
|
|
{
|
|
private string streamUrl;
|
|
private bool isCapturing;
|
|
private object lockSyncObject;
|
|
private volatile bool isFrameRequested;
|
|
|
|
public event CameraEvent OnVideoFrameReceived;
|
|
public event CameraEvent OnOneVideoFrameRequested;
|
|
|
|
public Camera(string streamUrl)
|
|
{
|
|
this.streamUrl = streamUrl;
|
|
isCapturing = true;
|
|
isFrameRequested = false;
|
|
lockSyncObject = new object();
|
|
}
|
|
|
|
public void Startcapture()
|
|
{
|
|
Thread readVideoStreamThread = new Thread(new ThreadStart(ReadVideoStream));
|
|
readVideoStreamThread.IsBackground = true;
|
|
readVideoStreamThread.Start();
|
|
}
|
|
|
|
public void RequestCaptureOneFrame()
|
|
{
|
|
isFrameRequested = true;
|
|
}
|
|
|
|
public void ReadVideoStream()
|
|
{
|
|
VideoCapture videoCapture = new VideoCapture();
|
|
Mat videoFrame = new Mat();
|
|
if (!videoCapture.Open(streamUrl))
|
|
{
|
|
return;
|
|
}
|
|
|
|
while (true)
|
|
{
|
|
Thread.Sleep(50); //Stream Thread Sleep
|
|
//Thread.Sleep(40); //Video Thread Sleep
|
|
if (!isCapturing)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (videoCapture.Read(videoFrame) && videoFrame.Width > 0 && videoFrame.Height > 0)
|
|
{
|
|
OnVideoFrameReceived?.Invoke(videoFrame);
|
|
if (isFrameRequested)
|
|
{
|
|
OnOneVideoFrameRequested?.Invoke(videoFrame);
|
|
isFrameRequested = false;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
public void PauseCapture()
|
|
{
|
|
lock (lockSyncObject)
|
|
{
|
|
isCapturing = false;
|
|
}
|
|
}
|
|
}
|
|
}
|