Skip to content

Instantly share code, notes, and snippets.

@0V
Last active August 29, 2015 14:16
Show Gist options
  • Save 0V/f1ab148dd3d6328457e8 to your computer and use it in GitHub Desktop.
Save 0V/f1ab148dd3d6328457e8 to your computer and use it in GitHub Desktop.
OpenCvSharp で Web カメラから動画を保存
using OpenCvSharp;
using OpenCvSharp.CPlusPlus;
using System;
namespace OpenCvSharpSample.Samples
{
public class CaptureIO
{
public static void CameraSave(int cameraId, int fps, int second, bool putText = true)
{
var frameSize = new Size(640, 480);
int frameCount = fps * second;
using (var writer = new VideoWriter("output.avi", FourCC.DIVX, fps, frameSize))
using (var capture = new VideoCapture(cameraId))
using (var window = new Window("Capture #" + cameraId))
{
if (!capture.IsOpened())
{
throw new InvalidOperationException("カメラが開けませんでした。");
}
try
{
Mat mat = new Mat();
var textPoint = new CvPoint(frameSize.Width - 410, frameSize.Height - 10);
var textFontFace = FontFace.HersheyComplexSmall;
var textColor = new CvColor(200, 0, 50);
capture.FrameHeight = frameSize.Height;
capture.FrameWidth = frameSize.Width;
while (frameCount-- > 0 && Cv2.WaitKey(1000 / fps) < 0)
{
capture.Read(mat);
if (putText)
{
mat.PutText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff K"), textPoint, textFontFace, 1, textColor);
}
window.ShowImage(mat);
writer.Write(mat);
}
}
catch (OpenCVException e)
{
throw new InvalidOperationException("読み込んだ画像を表示できませんでした。", e);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment