我正在尝试通过Unity调用OpenCV方法。我在Visual Studio中编译了该dll,然后将其导入到Unity中,它确实起作用。
我将C#中的纹理数据分配为字节数组,并将其作为指针传递给C ++方法。 C ++代码看起来像这样
extern "C" void __declspec(dllexport) __stdcall Init(ushort* data, int width, int height)
{
// I tested this part and it works. After calling this method all of the bytes are changed in my byte array in C#.
for (int i = 0; i < width * height * 3; i++)
data[i] = 0;
// To initialize Mat I'm using this constructor.
Mat src(height, width, CV_8UC3, data);
Mat bw;
// Calling OpenCV method to convert colors. This part doesn't do anything to my byte array.
cvtColor(src, bw, COLOR_RGB2GRAY);
}
和C#端
internal static class OpenCVInterop
{
[DllImport("ConsoleApplication2")]
internal static extern void Init(IntPtr data, int width, int height);
}
public class OpenCVFaceDetection : MonoBehaviour
{
void Start()
{
byte[] buffer = inputTexture.GetRawTextureData();
int width = inputTexture.width;
int height = inputTexture.height;
unsafe
{
fixed (byte* p = buffer)
{
IntPtr ptr = (IntPtr)p;
OpenCVInterop.Init(ptr, width, height);
}
}
}
}
据我了解,OpenCV方法应该获取我的数据并对其进行操作,因此在调用 cvtColor 方法后,应该更改我的字节数组,但不会发生。我花了无数个小时在网上搜索并测试各种不同的东西,并且陷入困境。