I have been digging through this for a while now, but I still can't find the source of the problem yet.
First, please know that all videos are 15 seconds each, 450 frames total. Frames are getting resized later to 50x50.
Using EmguCv, I am using the below routine to get all frames of a video:
public void PopulateAllFrames()
{
int FramesCount = 0;
try
{
FramesCount = (int)capture.GetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_COUNT);
for (int i = 0; i < FramesCount; i++)
{
var frame = capture.QueryGrayFrame(); // Error here
var resized = frame.Resize(ImageWidth, ImageHeight, Emgu.CV.CvEnum.INTER.CV_INTER_LINEAR);
AllFrames.Add(resized.Copy());
}
capture.Dispose();
GC.Collect();
}
catch (Exception ex)
{ }
}
The above works fine when I load any video on a button click:
private void SelectAVideo_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog OpenFile = new OpenFileDialog();
if (OpenFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
OriginalVideo = new MyVideo(OpenFile.FileName, true);
OriginalVideo.PopulateAllFrames();
}
catch (Exception ex)
{}
}
But it does not work on some videos when I load a directory of 25 videos. The passed videos are the same videos everytime, and the "errored" videos are also the same every time:
private void LoadDirectory_Click(object sender, EventArgs e)
{
try
{
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && fbd.SelectedPath != null)
{
AllVideos = new List<MyVideo>();
AllVideosFileNames = Directory.GetFiles(fbd.SelectedPath).ToList();
for (int i = 0; i < AllVideosFileNames.Count(); i++) // loop the rest of the videos, start from the 5th video and till the end
{
MyVideo CurrentVideo = new MyVideo(AllVideosFileNames[i], false);
CurrentVideo.PopulateAllFrames();
AllVideos.Add(CurrentVideo);
}
}
catch (Exception ex)
{ }
}
I am getting OutOfMemoryException
whenever I hit QueryGrayFrame()
, on the same group of videos every time I execute, even if I load only 10 videos. And with no pattern (means error does not pop just on the last 10 indexes.. etc). Knowing that videos are really small, And if I load any of those videos separately, it works fine.
How can I fix this issue?
As mentioned in the comments, I only needed to .Dispose()
my variables, as I did not think of that since my videos were small. Turned out they are taking a lot of memory nevertheless. so doing this fixed the problem:
for (int i = 0; i < FramesCount; i++)
{
var frame = capture.QueryGrayFrame(); // Error here
var resized = frame.Resize(ImageWidth, ImageHeight, Emgu.CV.CvEnum.INTER.CV_INTER_LINEAR);
AllFrames.Add(resized.Copy());
frame.Dispose();
resized.Dispose();
}