2020-06-19 18:39:08 +02:00
|
|
|
|
using System;
|
|
|
|
|
using System.Drawing;
|
|
|
|
|
using System.Threading;
|
|
|
|
|
using OpenCvSharp;
|
|
|
|
|
using OpenCvSharp.Extensions;
|
|
|
|
|
|
|
|
|
|
namespace squirrowse.client
|
|
|
|
|
{
|
|
|
|
|
public class Webcam
|
|
|
|
|
{
|
|
|
|
|
private static VideoCapture capture;
|
|
|
|
|
private static Mat frame;
|
|
|
|
|
private static Byte[] image;
|
|
|
|
|
private static Thread camera;
|
|
|
|
|
private static bool isCameraRunning;
|
|
|
|
|
private readonly bool imagetakinginprogress = false;
|
|
|
|
|
|
|
|
|
|
public Webcam(bool AutoActivate = true)
|
|
|
|
|
{
|
|
|
|
|
if (AutoActivate) Initalize();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Initalize()
|
|
|
|
|
{
|
|
|
|
|
CaptureCamera();
|
|
|
|
|
isCameraRunning = true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void CaptureCamera()
|
|
|
|
|
{
|
|
|
|
|
camera = new Thread(CaptureCameraCallback);
|
|
|
|
|
camera.Start();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void CaptureCameraCallback()
|
|
|
|
|
{
|
|
|
|
|
Thread.Sleep(1);
|
|
|
|
|
if (!isCameraRunning) return;
|
|
|
|
|
frame = new Mat();
|
|
|
|
|
capture = new VideoCapture(0);
|
|
|
|
|
capture.Open(0);
|
|
|
|
|
if (!capture.IsOpened()) return;
|
|
|
|
|
while (isCameraRunning)
|
|
|
|
|
{
|
|
|
|
|
capture.Read(frame);
|
|
|
|
|
image = frame.ToBytes();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public byte[] GetBitmap()
|
|
|
|
|
{
|
|
|
|
|
if (!isCameraRunning) throw new Exception("Cannot take picutre if the camera is not initalized!");
|
|
|
|
|
while (imagetakinginprogress)
|
|
|
|
|
{
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
{
|
2020-06-19 21:08:30 +02:00
|
|
|
|
Thread.Sleep(100);
|
2020-06-19 18:39:08 +02:00
|
|
|
|
return image;
|
2020-06-19 21:08:30 +02:00
|
|
|
|
|
2020-06-19 18:39:08 +02:00
|
|
|
|
}
|
|
|
|
|
catch
|
|
|
|
|
{
|
2020-06-19 21:08:30 +02:00
|
|
|
|
Thread.Sleep(100);
|
2020-06-19 18:39:08 +02:00
|
|
|
|
return image;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Deinitialize()
|
|
|
|
|
{
|
|
|
|
|
camera.Abort();
|
|
|
|
|
capture.Release();
|
|
|
|
|
isCameraRunning = false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
~Webcam()
|
|
|
|
|
{
|
|
|
|
|
Deinitialize();
|
|
|
|
|
capture.Dispose();
|
|
|
|
|
frame.Dispose();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|