接上一章内容,OpenCV可以实现VisionPro、VM一样的视觉操作,也同样可以连接相机;
代码如下:
using (VideoCapture capture = new VideoCapture(0))
{
if (!capture.IsOpened())
{
MessageBox.Show("摄像头连接失败!!!");
return;
}
using (Window windowRaw = new Window("相机拍摄"))
{
Mat currentFrame = new Mat();
while (true)
{
capture.Read(currentFrame);
if (currentFrame.Empty())
{
MessageBox.Show("无法读取图像帧");
break;
}
Cv2.ImShow(windowRaw.Name, currentFrame);
int key = Cv2.WaitKey(1);
if (key == 27) // ESC键
{
break;
}
else if (key == 32) // 空格键
{
string savePath = "文件地址";
bool result = Cv2.ImWrite(savePath, currentFrame);
if (savePath!=null)
{
savePath=null;
}
MessageBox.Show(result ? $"图像已保存到 {savePath}" : "保存图像失败");
}
}
}capture.Release();
Cv2.DestroyAllWindows();
}
点击空格后可以将相机拍摄的图像进行保存,再次点击即可删除这张图片并保存一张新的图片;
可以配合下面代码使用
if (p1.Image != null)
{
p1.Image.Dispose();
p1.Image = null;
}
else
{
p1.Image = Image.FromFile("文件地址");
}
这串代码可以使保存的图像显示在PictureBox控件上,也可以进行清除。(在按下第二个空格前需要确保PictureBox控件里没有显示图片,不然会触发图像保存失败)
OS:好像还有漏洞。。。