Search code examples
opencvc++-climat

Convert array<System:Byte>^ to Mat


How do I convert an array<System:Byte>^ to a Mat in openCV. I am being passed a array<System:Byte>^ in c++/cli, but I need to convert it to Mat to be able to read it and display it.


Solution

  • You can use constructor Mat::Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP). The conversion may look like this.

    void byteArray2Mat(array<System::Byte>^ byteArray, cv::Mat &output)
    {
        pin_ptr<System::Byte> p = &byteArray[0];
        unsigned char* pby = p;
        char* pch = reinterpret_cast<char*>(pby);
    
        // assuming your input array has 2 dimensions.
        int rows = byteArray->GetLength(0);
        int cols = byteArray->GetLength(1);
        output = cv::Mat(rows, cols, CV_8UC1, (void*)pch)
    }
    

    I don't have c++/CLI to test the program and this may not be most efficient method. At least it should give you an idea on how to get started.