我尝试从Emgu示例文件夹中调整示例MotionDetection。我改变的唯一重要的事情是我不是直接从网络摄像头捕获图像,而是创建Image<,>来自Bitmap。基本上不是
using (Image<Bgr, Byte> image = _capture.RetrieveBgrFrame())
我用
using (Image<Bgr, Byte> image = new Image<Bgr, Byte>(bmp))
我使用其他方法从网络摄像头捕获的bmp
是Bitmap
。
我使用和改编的部分:
public Bitmap ProcessFrame(Bitmap bmp)
{
using (Image<Bgr, byte> image = new Image<Bgr, byte>(bmp))
using (MemStorage storage = new MemStorage())
{
if (_forgroundDetector == null)
{
_forgroundDetector = new BGStatModel<Bgr>(image, Emgu.CV.CvEnum.BG_STAT_TYPE.FGD_STAT_MODEL);
}
_forgroundDetector.Update(image);
_motionHistory.Update(_forgroundDetector.ForegroundMask);
#region get a copy of the motion mask and enhance its color
double[] minValues, maxValues;
Point[] minLoc, maxLoc;
_motionHistory.Mask.MinMax(out minValues, out maxValues, out minLoc, out maxLoc);
Image<Gray, Byte> motionMask = _motionHistory.Mask.Mul(255.0 / maxValues[0]);
#endregion
image[0] = motionMask;
double minArea = 100;
storage.Clear();
Seq<MCvConnectedComp> motionComponents = _motionHistory.GetMotionComponents(storage);
foreach (MCvConnectedComp comp in motionComponents)
{
if (comp.area < minArea) continue;
double angle, motionPixelCount;
_motionHistory.MotionInfo(comp.rect, out angle, out motionPixelCount);
if (motionPixelCount < comp.area * 0.05) continue;
DrawMotion(image, comp.rect, angle, new Bgr(Color.Red));
}
double overallAngle, overallMotionPixelCount;
_motionHistory.MotionInfo(motionMask.ROI, out overallAngle, out overallMotionPixelCount);
DrawMotion(image, motionMask.ROI, overallAngle, new Bgr(Color.Green));
return image.ToBitmap();
}
}
private static void DrawMotion(Image<Bgr, Byte> image, Rectangle motionRegion, double angle, Bgr color)
{
float circleRadius = (motionRegion.Width + motionRegion.Height) >> 2;
Point center = new Point(motionRegion.X + motionRegion.Width >> 1, motionRegion.Y + motionRegion.Height >> 1);
CircleF circle = new CircleF(
center,
circleRadius);
int xDirection = (int)(Math.Cos(angle * (Math.PI / 180.0)) * circleRadius);
int yDirection = (int)(Math.Sin(angle * (Math.PI / 180.0)) * circleRadius);
Point pointOnCircle = new Point(
center.X + xDirection,
center.Y - yDirection);
LineSegment2D line = new LineSegment2D(center, pointOnCircle);
image.Draw(circle, color, 1);
image.Draw(line, color, 2);
}
然而,该程序抛出异常:
An unhandled exception of type 'Emgu.CV.Util.CvException' occurred in Emgu.CV.dll. Additional information: OpenCV: Failed to allocate 121651200 bytes
这里:
_forgroundDetector = new BGStatModel<Bgr>(image, Emgu.CV.CvEnum.BG_STAT_TYPE.FGD_STAT_MODEL);
Windows 7,64x程序构建为&#39;任何CPU&#39;,&#39;首选32位&#39;。我使用最新的Emgu 2.4.9-beta。
当我使用1920x1080位图(3MB)时会发生这种情况。当我在应用程序窗口中使用两个不同的摄像头(704x576和352x288,我修改了程序,因此我可以从多个摄像头获得图像)时,它也会发生(虽然不是单个低分辨率的)。当我没有用这种方法检测运动时,程序运行没有问题。