簡體   English   中英

使用 C++ openCV 處理顫振圖像

[英]Processing flutter images with C++ openCV

我正在做一個項目,我想使用 C++ OpenCV 處理我的圖像。

為簡單起見,我只想將Uint8List轉換為cv::Mat並返回。

按照教程,我設法制作了一個不會使應用程序崩潰的管道。 具體來說:

  1. 我在.cpp中創建了一個函數,該函數將指針指向我的Uint8ListrawBytes ,並將其編碼為.jpg
    int encodeIm(int h, int w, uchar *rawBytes, uchar **encodedOutput) {
        cv::Mat img = cv::Mat(h, w, CV_8UC3, rawBytes); //CV_8UC3
        vector<uchar> buf;
        cv:imencode(".jpg", img, buf); // save output into buf. Note that Dart Image.memory can process either .png or .jpg, which is why we're doing this encoding
        *encodedOutput = (unsigned char *) malloc(buf.size());
        for (int i=0; i < buf.size(); i++)
            (*encodedOutput)[i] = buf[i];
        return (int) buf.size();
    }
  1. 然后我在.dart中編寫了一個函數,該函數調用我的 c++ encodeIm(int h, int w, uchar *rawBytes, uchar **encodedOutput)
   //allocate memory heap for the image
   Pointer<Uint8> imgPtr = malloc.allocate(imgBytes.lengthInBytes);

   //allocate just 8 bytes to store a pointer that will be malloced in C++ that points to our variably sized encoded image
   Pointer<Pointer<Uint8>> encodedImgPtr = malloc.allocate(8);

   //copy the image data into the memory heap we just allocated
   imgPtr.asTypedList(imgBytes.length).setAll(0, imgBytes);

   //c++ image processing
   //image in memory heap -> processing... -> processed image in memory heap
   int encodedImgLen = _encodeIm(height, width, imgPtr, encodedImgPtr);
   //

   //retrieve the image data from the memory heap
   Pointer<Uint8> cppPointer = encodedImgPtr.elementAt(0).value;
   Uint8List encodedImBytes = cppPointer.asTypedList(encodedImgLen);
   //myImg = Image.memory(encodedImBytes);
   return encodedImBytes;
   //free memory heap
   //malloc.free(imgPtr);
   //malloc.free(cppPointer);
   //malloc.free(encodedImgPtr); // always frees 8 bytes
 }
  1. 然后我通過以下方式將 c++ 與 dart 鏈接起來:
final DynamicLibrary nativeLib = Platform.isAndroid
    ? DynamicLibrary.open("libnative_opencv.so")
    : DynamicLibrary.process();

final int Function(int height, int width, Pointer<Uint8> bytes, Pointer<Pointer<Uint8>> encodedOutput) 
_encodeIm = nativeLib
        .lookup<NativeFunction<Int32 Function(Int32 height, Int32 width, 
Pointer<Uint8> bytes, Pointer<Pointer<Uint8>> encodedOutput)>>('encodeIm').asFunction();
  1. 最后,我通過以下方式在 Flutter 中顯示結果:
Image.memory(...)

現在,管道沒有崩潰,這意味着我沒有完全搞砸內存處理,但它也沒有返回原始圖像,這意味着我確實在某個地方搞砸了。

原圖:
1

管道輸出:
2

感謝 Richard Heap 在評論中的指導,我設法通過更改我的矩陣定義來修復管道

cv::Mat img = cv::Mat(h, w, CV_8UC3, rawBytes);

vector<uint8_t> buffer(rawBytes, rawBytes + inBytesCount);
Mat img = imdecode(buffer, IMREAD_COLOR);

其中inBytesCountimgBytes的長度。

如果您覺得這很有用,請對問題和答案都投贊成票,因為我使用業力來支付賞金。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM