Acquire Images from a Stream (Console)
We continue with the loaded stream from Loading Image Stream Sources (Console):
The goal is to write all images from that video stream as single images to a target folder. For simplicity we create a folder on the Desktop (everybody loves additional folders on the desktop ):
var targetDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "CvbNetDemo");
if (!Directory.Exists(targetDir))
Directory.CreateDirectory(targetDir);
From the post above we know the number of images in the video (ImageCount
= 300). So here is the snipped with the loop and the code to get the stream running:
stream.Start();
try
{
for (int i = 0; i < stream.ImageCount; i++)
{
using (StreamImage image = stream.Wait())
{
// Save here...
}
}
}
finally
{
stream.Stop();
}
So, stream.Start()
starts the acquisition, stream.Stop()
halts it and stream.Wait()
waits for the next image to arrive in the stream. The StreamImage
by default is only valid until the next call to Stream.Wait()
(after which it is Dispose
d). Thus using the using block (no pun intended) makes that clear in the code (the acquisition engine dosn’t double dispose - we take care of that ).
We also have learned how to save images – it will be easy to complete the app:
Snippet to put into Main()
var targetDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "CvbNetDemo");
if (!Directory.Exists(targetDir))
Directory.CreateDirectory(targetDir);
var aviPath = Path.Combine(SystemInfo.InstallPath, "Tutorial", "Foundation", "Videos", "Cycling (xvid).avi" );
using (var videoDevice = DeviceFactory.Open(aviPath))
{
var stream = videoDevice.Stream as IndexedStream;
stream.Start();
try
{
for (int i = 0; i < stream.ImageCount; i++)
{
using (StreamImage image = stream.Wait())
{
var targetFileName = Path.Combine(targetDir, string.Format("{0:000}.jpg", i));
image.Save(targetFileName);
}
}
}
finally
{
stream.Stop();
}
}