六 在窗体上画一个按钮,然后再按纽的下面写上如下的程序:
private void btnOpenImage_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "BMP文件|*.bmp|JPG文件|*.jpg|JPEG文件|*.jpeg|所有文件|*.*"; if (openFileDialog.ShowDialog() == DialogResult.OK) { CvInvoke.cvNamedWindow("打开图片"); IntPtr img = CvInvoke.cvLoadImage(openFileDialog.FileName, Emgu.CV.CvEnum.LOAD_IMAGE_TYPE.CV_LOAD_IMAGE_UNCHANGED); CvInvoke.cvShowImage("打开图片", img); this.img = img; CvInvoke.cvWaitKey(0); CvInvoke.cvReleaseImage(ref img); CvInvoke.cvDestroyWindow("打开图片"); } } 这样,我们就能用OpenCv的函数来打开和显示一个图片了。如果要保存图片可以如下: private void btnSaveImage_Click(object sender, EventArgs e) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "BMP文件|*.bmp|JPG文件|*.jpg|JPEG文件|*.jpeg|所有文件|*.*"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { CvInvoke.cvSaveImage(saveFileDialog.FileName, this.img); } } //如果要打开一个AVI视频文件,可以如下: private void btnOpenAVI_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "AVI文件|*.avi"; if (openFileDialog.ShowDialog() == DialogResult.OK) { CvInvoke.cvNamedWindow("打开视频"); IntPtr capture=CvInvoke.cvCreateFileCapture(openFileDialog.FileName); this.video = capture; IntPtr frame = new IntPtr(); while (true) { frame = CvInvoke.cvQueryFrame(capture); CvInvoke.cvShowImage("打开视频", frame); //if (!frame) break; int c = CvInvoke.cvWaitKey(20); if (c == 13) break; } //this.video = capture; CvInvoke.cvWaitKey(0); CvInvoke.cvReleaseCapture(ref capture); CvInvoke.cvDestroyWindow("打开视频"); } } //要保存一个AVI文件可以如下: private void btnSaveAVI_Click(object sender, EventArgs e) { IntPtr avi = this.video; SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "BMP文件|*.bmp|JPG文件|*.jpg|JPEG文件|*.jpeg|所有文件|*.*"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { IntPtr videoWriter = CvInvoke.cvCreateVideoWriter(saveFileDialog.FileName, -1, 20, new Emgu.CV.MCvSize(480, 500), 1); IntPtr capture=CvInvoke.cvCreateFileCapture(saveFileDialog.FileName); IntPtr frame = new IntPtr(); while (true) { frame = CvInvoke.cvQueryFrame(capture); CvInvoke.cvWriteFrame(videoWriter, frame); } } }