简体   繁体   English

如何在Swift中从C ++矩阵中检索值?

[英]How to retrieve value from C++ matrix in Swift?

I have a C++ function what returns a cv::Mat value 我有一个C ++函数,它返回一个cv::Mat

+(cv::Mat *) makeGray:(UIImage *) image {
    // Transform UIImage to cv::Mat
    cv::Mat imageMat;
    UIImageToMat(image, imageMat);

    //Transform image to grayscale
    cv::Mat grayMat;
    cv::cvtColor(imageMat, grayMat, CV_BGR2GRAY);
    return grayMat;
}

I call that function in Swift using: 我在Swift中使用以下函数调用该函数:

let grayMat = OpenCVWrapper.makeGray(photoImageView.image)

I know Swift doesn't import cv::Mat , what's the best alternative so that I get that array in one piece? 我知道Swift不会导入cv::Mat ,那么最好的替代方法是什么,这样我就可以将数组拆分成一个整体?

This should work.. Just convert the cv::Mat to a malloc 'd byte array and return that. 这应该工作..就在转换cv::Matmalloc “d字节数组,并返回。

+ (uint8_t *)makeGray:(UIImage *)image count:(uint32_t *)count {
    // Transform UIImage to cv::Mat
    cv::Mat imageMat;
    UIImageToMat(image, imageMat);

    //Transform image to grayscale
    cv::Mat grayMat;
    cv::cvtColor(imageMat, grayMat, CV_BGR2GRAY);

    int size = grayMat.total() * grayMat.elemSize();
    void *bytes = malloc(size);
    memcpy(bytes, grayMat.data, size);
    *count = size;
    return bytes;
}

Then on the swift side it should be an UnsafeMutablePointer<UInt8> with a count and you can free it by calling deallocate or convert it to an array of bytes. 然后从另一方面讲,它应该是一个带有计数的UnsafeMutablePointer<UInt8> ,您可以通过调用deallocate或将其转换为字节数组来释放它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM