Metacontext:
I am currently working on a game that uses opencv as a replacement for conventional inputs (keyboard, mouse, etc.). I am using Unity3D C # and opencv scripts in C ++ through DllImports. My goal is to create an image inside my game coming from opencv.
Code Context:
As usual in OpenCV, I use Mat to represent my image. This is how I export image bytes:
cv::Mat _currentFrame;
...
extern "C" byte * EXPORT GetRawImage()
{
return _currentFrame.data;
}
And here is how I import from C #:
[DllImport ("ImageInputInterface")]
private static extern IntPtr GetRawImage ();
...
public static void GetRawImageBytes (ref byte[] result, int arrayLength) {
IntPtr a = GetRawImage ();
Marshal.Copy(a, result, 0, arrayLength);
FreeBuffer(a);
}
Judging by how I understand OpenCV, I expect the byte array to be structured this way when serialized in the uchar pointer:
b1, g1, r1, b2, g2, r2, ...
I convert this BGR array to an RGB array using:
public static void BGR2RGB(ref byte[] buffer) {
byte swap;
for (int i = 0; i < buffer.Length; i = i + 3) {
swap = buffer[i];
buffer[i] = buffer[i + 2];
buffer[i + 2] = swap;
}
}
Finally, I use Unity LoadRawTextureDatato load bytes into the texture:
this.tex = new Texture2D(
ImageInputInterface.GetImageWidth(),
ImageInputInterface.GetImageHeight(),
TextureFormat.RGB24,
false
);
...
ImageInputInterface.GetRawImageBytes(ref ret, ret.Length);
ImageInputInterface.BGR2RGB(ref ret);
tex.LoadRawTextureData(ret);
tex.Apply();
Results:
, , - , , , , . :
[, ]

, , , , RGB, :
[ ]

[ ]

[ ]

:
[Spooky Lines]

:
[ ]

:
, OpenCV? , , Unity LoadRawTextureData, - ?
OpenCV Mat.data?
UPDATE
@Programmer .
[ ]

script, - . BGR2RGBA, RGB2RGBA:
extern "C" void EXPORT GetRawImage( byte *data, int width, int height )
{
cv::Mat resizedMat( height, width, _currentFrame.type() );
cv::resize( _currentFrame, resizedMat, resizedMat.size(), cv::INTER_CUBIC );
cv::Mat argbImg;
cv::cvtColor( resizedMat, argbImg, CV_BGR2RGBA );
std::memcpy( data, argbImg.data, argbImg.total() * argbImg.elemSize() );
}