这几天在做车流量统计,用的是Emgu,查看Emgu安装文件下的Examples例子,经过修改后,第一次选择视频进行车辆统计的时候没有问题,但是不关闭窗体第二次选择视频进行统计的时候会出现内存分配失败的问题。搜了很多方法还是没有解决。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.UI;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.CV.VideoSurveillance;
using System.Diagnostics;
using System.Threading;
namespace TrafficStatistics
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private static MCvFont _font = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_SIMPLEX, 1.0, 1.0);//定义显示的字体
private static Capture cameraCapture;
private static BlobTrackerAuto<Bgr> tracker;//定义一个块状的汽车跟踪器
private static FGDetector<Bgr> detector;//定义一个背景建模检测器
private object lockObject = new object(); //用于锁定的对象
private Stopwatch sw = new Stopwatch(); //计时器
// Image<Bgr, Byte> frame;//得到视频文件中的一帧
// bool stop = false;
/// <summary>
/// 打开视频文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
var dialog = new OpenFileDialog();
dialog.Filter = "视频文件|*.avi;*.rmvb;*.rm";
if (dialog.ShowDialog() == DialogResult.OK)
{
String fileName = dialog.FileName;
//cameraCapture = CvInvoke.cvCreateFileCapture(file);
try
{
cameraCapture = new Capture(fileName);
//cameraCapture.FlipHorizontal = ! cameraCapture.F
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
detector = new FGDetector<Bgr>(FORGROUND_DETECTOR_TYPE.FGD);
tracker = new BlobTrackerAuto<Bgr>();
Application.Idle += ProcessFrame;
}
void ProcessFrame(object sender, EventArgs e)
{
using (MemStorage stor = new MemStorage())
//得到视频文件中的一帧
{
Image<Bgr, Byte> frame = cameraCapture.QueryFrame();
if (frame != null)
{
frame._SmoothGaussian(3); //filter out noises:对于当前的图像进行高斯平滑处理过滤噪声
#region use the BG/FG detector to find the forground mask
detector.Update(frame);//更新当前图像
Image<Gray, Byte> forgroundMask = detector.ForegroundMask;//得到前景图像
#endregion
try
{
//tracker.Process(frame, forgroundMask);//处理图像产生一种色调掩模,调用这句话会出现内存不足异常
//tracker.Process(frame);
tracker.Process(cameraCapture.QuerySmallFrame().PyrUp());//只传入一半的图片进行识别和跟踪
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
foreach (MCvBlob blob in tracker)
{
frame.Draw((Rectangle)blob, new Bgr(255.0, 255.0, 255.0), 2);
//frame.Draw(blob.ID.ToString(), ref _font, Point.Round(blob.Center), new Bgr(255.0, 255.0, 255.0));
vehicleStatTextBox.Text = blob.ID.ToString();//统计车辆数目
}
imageBox1.Image = frame;
//tracker.Dispose();
}
}
}
}
}