AccessViolationExeption in Parallel.ForEach loop
-
08-10-2019 - |
Question
I'm trying to execute this code in .NET using EmguCV:
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);
});
This is my GetPicturesFromCamera() Method:
static IEnumerable<Bitmap> GetImagesFromCamera()
{
Camera cam = new Camera();
cam.StartCapture();
while (true)
{
yield return new Image<Gray, Byte>(cam.getBitmap());// <=== AccessViolationException
}
}
At the marked point I always get a AccessViolationException saying "Attempted to read or write protected memory. This is often an indication that other memory is corrupt.", but I don't find the mistake.
Can you figure it out?
EDIT:
I tried it sequencialy too, this way it works:
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);
};
but this way it doesn't:
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);
};
Solution
I found a solution: I had to put all the code in the Camera class into the GetImagesFromCamera method, but I have no idea why.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow