1
我試圖使用EmguCV在.NET中執行此代碼:AccessViolationExeption在Parallel.ForEach環
Parallel.ForEach<Bitmap>(GetImagesFromCamera(), bmp =>
{
Image<Gray, Byte> src = new Image<Gray, Byte>(bmp);
Image<Gray, Byte> dest = new Image<Gray, Byte>(src.Width, src.Height);
CvInvoke.cvThreshold(src, dest, 100, 255, Emgu.CV.CvEnum.THRESH.CV_THRESH_BINARY);
form.setImage(dest);
});
這是我GetPicturesFromCamera()方法:
static IEnumerable<Bitmap> GetImagesFromCamera()
{
Camera cam = new Camera();
cam.StartCapture();
while (true)
{
yield return new Image<Gray, Byte>(cam.getBitmap());// <=== AccessViolationException
}
}
在標記點我總是會得到一個AccessViolationException異常,說「嘗試讀取或寫入受保護的內存,這通常表示其他內存已損壞」, 但我沒有發現錯誤。
你能弄明白嗎?
編輯:
我試了一下sequencialy過,這樣它的工作原理:
foreach (var bmp in GetImagesFromCamera())
{
Image<Gray, Byte> dest = new Image<Gray, Byte>(bmp.Width, bmp.Height);
CvInvoke.cvThreshold(bmp, dest, 100, 255, Emgu.CV.CvEnum.THRESH.CV_THRESH_BINARY);
form.setImage(dest);
};
,但這種方式並不:
foreach (var bmp in GetImagesFromCamera())
{
Image<Gray, Byte> dest = new Image<Gray, Byte>(bmp.Width, bmp.Height);
Image<Gray, Byte> tmp = new Image<Gray, Byte>(bmp.Width, bmp.Height);
CvInvoke.cvThreshold(bmp, dest, 100, 255, Emgu.CV.CvEnum.THRESH.CV_THRESH_BINARY);
CvInvoke.cvErode(dest, tmp, IntPtr.Zero, 2);
CvInvoke.cvDilate(tmp, dest, IntPtr.Zero, 2);
form.setImage(dest);
};