Skip to content

Instantly share code, notes, and snippets.

@shimat
Last active April 12, 2017 01:23
Show Gist options
  • Save shimat/ca55c3f2a67a7a99322e32cc0f577f38 to your computer and use it in GitHub Desktop.
Save shimat/ca55c3f2a67a7a99322e32cc0f577f38 to your computer and use it in GitHub Desktop.
OpenCvSharp3のMatに、OpenCV2系でデコードした画像データをコピーする
using System;
using System.Runtime.InteropServices;
using OpenCvSharp; // OpenCvSharp3
static class MyDecoder
{
public static unsafe Mat FromImageDataByOpenCV2(
[NotNull] byte[] imageData,
ImreadModes modes = ImreadModes.Color)
{
if (imageData == null)
throw new ArgumentNullException(nameof(imageData));
fixed (byte* pImageData = imageData)
{
CvMat src;
cvInitMatHeader(&src, imageData.Length, 1, CV_8U, pImageData, CV_AUTO_STEP);
CvMat* decoded = null;
try
{
int isColor = (int)modes;
decoded = cvDecodeImageM(&src, isColor);
var dst = new Mat(decoded->rows, decoded->cols, decoded->type);
long srcLength = decoded->step * decoded->rows;
long dstLength = dst.Step() * dst.Rows;
Buffer.MemoryCopy(decoded->ptr, dst.Data.ToPointer(), dstLength, srcLength);
return dst;
}
finally
{
if (decoded != null)
cvReleaseMat(&decoded);
}
}
}
private const int CV_8U = 0;
private const int CV_AUTO_STEP = 0x7fffffff;
private const int CV_LOAD_IMAGE_GRAYSCALE = 0;
private const int CV_LOAD_IMAGE_COLOR = 1;
[DllImport("opencv_highgui2410.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
private static extern unsafe CvMat* cvDecodeImageM(CvMat* buf, int iscolor);
[DllImport("opencv_core2410.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
private static extern unsafe CvMat* cvInitMatHeader(CvMat* mat, int rows, int cols, int type, void* data, int step);
[DllImport("opencv_core2410.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
private static extern unsafe void cvReleaseMat(CvMat** mat);
[StructLayout(LayoutKind.Sequential)]
private unsafe struct CvMat
{
public int type;
public int step;
public int* refcount;
public int hdr_refcount;
public byte* ptr;
public int rows;
public int cols;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment