示例:使用EmguCV视频截图
步骤:
1、 创建一个Windows窗体应用程序,将Form1的Name属性改为“RetrievePic”,Text属性改为“视频截图RetrievePic
2、 给窗体添加一个TrackBar,在事件属性中双击ValueChanged,系统自动生成事件代码
3、 给窗体添加一个PictureBox,将SizeModel设置为AutoSize
4、 添加一个视频文件“2.avi”
5、 添加EmguCV的引用,这里添加最常用的3个【Emgu.CV.dll、Emgu.CV.UI.dll、Emgu.Util.dll】
6、 添加命名空间
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using System.Runtime.InteropServices;
7、 编写代码
public RetrievePic()
{
InitializeComponent();
init();
}
/// <summary>
/// 初始化
/// </summary>
private void init()
{
IntPtr capture = CvInvoke.cvCreateFileCapture("2.avi");
IntPtr iplImage = CvInvoke.cvQueryFrame(capture);
//视频总帧数
int totalFrames = (int)CvInvoke.cvGetCaptureProperty(capture,CAP_PROP.CV_CAP_PROP_FRAME_COUNT);
trackBar1.Minimum = 0;
trackBar1.Maximum = totalFrames;
pictureBox1.Image = ConvertIntPrToBitmap(iplImage);
CvInvoke.cvReleaseCapture(ref capture);
}
private void trackBar1_ValueChanged(object sender, EventArgs e)
{
IntPtr capture = CvInvoke.cvCreateFileCapture("2.avi");
CvInvoke.cvSetCaptureProperty(capture, CAP_PROP.CV_CAP_PROP_POS_FRAMES, trackBar1.Value);
IntPtr iplImage = CvInvoke.cvQueryFrame(capture);
pictureBox1.Image = ConvertIntPrToBitmap(iplImage);
CvInvoke.cvReleaseCapture(ref capture);
}
/// <summary>
/// 将IplImage*转换为Bitmap(注:在OpenCV中IplImage* 对应EmguCV的IntPtr类型)
/// </summary>
/// <param name="ptrImage"></param>
/// <returns>Bitmap对象</returns>
public static Bitmap ConvertIntPrToBitmap(IntPtr ptrImage)
{
//将IplImage指针转换成MIplImage结构
MIplImage mi = (MIplImage)Marshal.PtrToStructure(ptrImage, typeof(MIplImage));
Image<Bgr, Byte> image = new Image<Bgr, Byte>(mi.width, mi.height, mi.widthStep, mi.imageData);
return image.ToBitmap();
}