新手探路:openCVSharp,源码及程序员github在此
转载请在文章开头点明本文作者及原链接
前言
多摄像头
一、vs使用openCVSharp
Nuget安装
- OpenCvSharp4
- OpenCvSharp4.Extensions
- OpenCvSharp4.runtime.win
二、代码
1.导入摄像头
代码如下(示例):
VideoCapture capture1;
VideoCapture capture2;
VideoCapture capture3;
Mat frame1;
Mat frame2;
Mat frame3;
Bitmap image3;
Bitmap image2;
Bitmap image1;
int isCameraRunning = 0;
BackgroundWorker cameraworker1;
public Form1()
{
InitializeComponent();
capture1 = new VideoCapture();
capture2 = new VideoCapture();
capture3 = new VideoCapture();
cameraworker1 = new BackgroundWorker();
cameraworker1.WorkerReportsProgress = true;
cameraworker1.WorkerSupportsCancellation = true;
cameraworker1.DoWork += Cameraworker_DoWork;
cameraworker1.ProgressChanged += Cameraworker_ProgressChanged;
openCamera();
}
private void openCamera()
{
capture1.Open(0);
capture2.Open(1);
capture3.Open(2);
if (!capture1.IsOpened())
{
Close();
MessageBox.Show("fail1");
}
if (!capture2.IsOpened())
{
Close();
MessageBox.Show("fail2");
}
if (!capture3.IsOpened())
{
Close();
MessageBox.Show("fail3");
}
button1.Text = "close";
cameraworker1.RunWorkerAsync();
}
2.实时显示(耗时操作)
private void Cameraworker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Bitmap[] frameBitmap = e.UserState as Bitmap[];
pictureBox1.Image?.Dispose();
pictureBox1.Image = frameBitmap[0];
pictureBox2.Image?.Dispose();
pictureBox2.Image = frameBitmap[1];
pictureBox3.Image?.Dispose();
pictureBox3.Image = frameBitmap[2];
}
private void Cameraworker_DoWork(object sender, DoWorkEventArgs e)
{
var ccdWorker = (BackgroundWorker)sender;
while (!ccdWorker.CancellationPending)
{
Bitmap[] bitmaps = new Bitmap[3];
Mat mat1 = capture1.RetrieveMat();
Mat mat2 = capture2.RetrieveMat();
Mat mat3 = capture3.RetrieveMat();
bitmaps[0] = BitmapConverter.ToBitmap(mat1);
bitmaps[1] = BitmapConverter.ToBitmap(mat2);
bitmaps[2] = BitmapConverter.ToBitmap(mat3);
ccdWorker.ReportProgress(0, bitmaps);
Thread.Sleep(50);
}
}
3.设置分辨率
if (capture1.Set(VideoCaptureProperties.FrameHeight, 1080)&& capture1.Set(VideoCaptureProperties.FrameWidth, 1920))
if (capture2.Set(VideoCaptureProperties.FrameHeight, 1080)&& capture2.Set(VideoCaptureProperties.FrameWidth, 1920))
if (capture3.Set(VideoCaptureProperties.FrameHeight, 1080) && capture3.Set(VideoCaptureProperties.FrameWidth, 1920))
MessageBox.Show("succed");
总结
打工真难,解决问题真快乐