Skip to content

Instantly share code, notes, and snippets.

@0V
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0V/3df7d21e339fcca9a543 to your computer and use it in GitHub Desktop.
Save 0V/3df7d21e339fcca9a543 to your computer and use it in GitHub Desktop.
メモリリークしない
// using OpenCvSharp;
// using OpenCvSharp.CPlusPlus;
// リソースを自分の管理下において明示的に開放すればメモリリークしない
public static void CanAllocateMemoryMethod(int cameraId)
{
using (var capture = new VideoCapture(cameraId))
{
var srcMat = new Mat();
while (Cv2.WaitKey(1) < 0)
{
capture.Read(srcMat);
var grayMat = srcMat.CvtColor(ColorConversion.BgrToGray);
var binaryMat = grayMat.Threshold(100, 255, ThresholdType.Binary);
var dstMat = binaryMat.CvtColor(ColorConversion.GrayToBgr);
Cv2.ImShow("src", srcMat);
Cv2.ImShow("dst", dstMat);
grayMat.Dispose();
binaryMat.Dispose();
dstMat.Dispose();
}
}
}
// OpenCV2 C++ API ライクに書いてもメモリリークしない
public static void CanAllocateMemoryMethod2(int cameraId)
{
using (var capture = new VideoCapture(cameraId))
{
var srcMat = new Mat();
var dstMat = new Mat();
while (Cv2.WaitKey(1) < 0)
{
capture.Read(srcMat);
Cv2.CvtColor(srcMat, dstMat, ColorConversion.BgrToGray);
Cv2.Threshold(dstMat, dstMat, 100, 255, ThresholdType.Binary);
Cv2.CvtColor(dstMat, dstMat, ColorConversion.GrayToBgr);
Cv2.ImShow("src", srcMat);
Cv2.ImShow("dst", dstMat);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment