I. Interface layout
- two
Button
- a
PictureBox
- a
BackgroundWorker cameraWorker
Second, function realization
2.1 Enabling the Camera
- Turn on the camera
- Check whether the camera is enabled. If no, prompt is displayed and exit
- Camera Background Task
cameraWorker
Began to run
private void openCameraBtn_Click(object sender, EventArgs e)
{
if (cameraWorker.IsBusy)
{
closeCamera();
}
else{ openCamera(); }}private void openCamera()
{
capture.Open(0, VideoCaptureAPIs.ANY);
if(! capture.IsOpened()) { Close(); MessageBox.Show("Failed to open camera.");
return;
}
openCameraBtn.Text = "Turn off the camera.";
cameraWorker.RunWorkerAsync();
}
private void closeCamera()
{
openCameraBtn.Text = "Turn on the camera.";
cameraWorker.CancelAsync();
capture.Release();
pictureBox1.Image = null;
}
Copy the code
2.2 Running Background Camera Tasks
while
Infinite loop- Obtaining a Camera
frameMat
- Converted to
Bitmap
- Copy to
pictureBox1
private void cameraWorker_DoWork(object sender, DoWorkEventArgs e)
{
var bgWorker = (BackgroundWorker)sender;
while(! bgWorker.CancellationPending) {using (var frameMat = capture.RetrieveMat())
{
var frameBitmap = BitmapConverter.ToBitmap(frameMat);
bgWorker.ReportProgress(0, frameBitmap);
}
Thread.Sleep(100); }}private void cameraWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
varframeBitmap = (Bitmap)e.UserState; pictureBox1.Image? .Dispose(); pictureBox1.Image = frameBitmap; }Copy the code
3. Exceptions are reported
System. TypeInitializationException: "" OpenCvSharp. Internal. NativeMethods" of type initializers throw an exception." Internal exception DllNotFoundException: DLL cannot be loaded "OpenCvSharpExtern" : specified module cannot be found. (Exception is from HRESULT:0x8007007E).Copy the code
Because there’s a little DLL missing
- Click to download OpenCVSharp DL.zip
- In the
Under the \ bin \ Debug \
Four, run,
- perfect
Five, Demo source code
OpenCVSharpDemo project source click to download
If you feel good, just click three times. (Like + Favorites + follow)