效果如下:
1.创建一个winform的窗体项目(框架.NET Framework 4.7.2)
2.Nuget引入opencv的c#程序包(版本最好和我一致)
3.后台代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenCvSharp;
using OpenCvSharp.Extensions;
namespace opencv读取摄像头
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;//取消跨线程检查
this.timer1.Start();
}
private VideoCapture capture;
private bool isopen = false;
private bool saveImgFlag = false;
private string filePath = "";
private void button1_Click(object sender, EventArgs e)
{
capture = new VideoCapture(0);
if (!capture.IsOpened())
{
MessageBox.Show("无法打开摄像头");
return;
}
isopen = true;
Thread video_th = new Thread(StartCapturing);
video_th.IsBackground = true;
video_th.Start();
}
public void StartCapturing()
{
Mat frame = new Mat();
while (true)
{
capture.Read(frame);//读取图像帧
if (frame.Empty())
{
break;
}
Bitmap bitmap = BitmapConverter.ToBitmap(frame);
if (saveImgFlag == true)
{
try
{
bitmap.Save(filePath, ImageFormat.Jpeg);
saveImgFlag = false;
MessageBox.Show("保存成功!");
}
catch (Exception ex)
{
}
}
pictureBox1.Image = bitmap;
pictureBox1.Refresh();
}
}
private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
// 设置对话框的标题
saveFileDialog.Title = "Save Image";
// 设置默认的文件名和文件类型过滤器
saveFileDialog.FileName = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");
saveFileDialog.Filter = "Image files (*.Png)|*.Png|Image files (*.Jpg)|*.Jpg";
// 显示对话框并获取用户的操作结果
DialogResult result = saveFileDialog.ShowDialog();
if (result == DialogResult.OK)
{
// 用户点击了保存按钮
filePath = saveFileDialog.FileName;
//string filter=saveFileDialog.Filter;
// 在这里进行保存文件的操作,例如:
// File.WriteAllText(filePath, "Hello, world!");
Console.WriteLine("File saved to: " + filePath);
}
else if (result == DialogResult.Cancel)
{
// 用户点击了取消按钮
Console.WriteLine("Save cancelled");
}
saveImgFlag = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
this.label1.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
}
}