美文网首页
matlab C++混合编程——opencv

matlab C++混合编程——opencv

作者: 侠之大者_7d3f | 来源:发表于2019-05-19 12:45 被阅读0次

Canny边缘检测

C++代码

#include<iostream>
#include<opencv2/opencv.hpp>
#include<mex.h>

/*
nlhs 输出参数个数
plhs 输出参数指针
nrhs 输入参数个数
prhs 输入参数指针
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{

    //获取输入矩阵的行、列
    int rows = mxGetM(prhs[0]);
    int cols = mxGetN(prhs[0]);

    //获取输入图像的指针
    unsigned char* img_ptr = (unsigned char*)mxGetPr(prhs[0]);

    //实例化Mat, 注意,matlab中数据是按列存储的,但是C++ opencv中图像是按行存放的,因此
    //在构造图像时候,构造为图像的转置,然后对图像进行一次转置就得到opencv中真实图像
    cv::Mat image = cv::Mat(cols, rows, CV_8UC1, img_ptr);
    cv::Mat image_;
    cv::transpose(image, image_);

    //Canny边缘检测
    cv::Mat dst;
    cv::Canny(image_, dst, 20, 50);

    plhs[0] = mxCreateNumericMatrix_700(rows, cols, mxClassID::mxUINT8_CLASS, mxComplexity::mxREAL);
    cv::Mat dst_ = cv::Mat(rows, cols, CV_8UC1, (unsigned char*)(mxGetPr(plhs[0])));
    cv::transpose(dst, dst_);
    

    //cv::imshow("canny", dst);
    //cv::waitKey(0);


}

matlab测试代码

clear;
clc;

image = imread('F:\\lena\\lena_gray.jpg');
canny_img = compute_canny(image);

imshow(canny_img)


image.png

Sobel边缘检测

C++代码

#include<opencv2/opencv.hpp>
#include<mex.h>
#include<opencvmex.hpp>


//https://blog.csdn.net/shaoxiaohu1/article/details/8269690
//https://blog.csdn.net/u012978091/article/details/51138505



void mexFunction(
    int           nlhs,           /* number of expected outputs */
    mxArray       *plhs[],        /* array of pointers to output arguments */
    int           nrhs,           /* number of inputs */
    const mxArray *prhs[]         /* array of pointers to input arguments */
) {

    /*
    判断matlab传入的数据类型,图像要求uint8
    */
    if (!mxIsUint8(prhs[0])) {
        std::runtime_error("Image data must be uint8 type!");
    }

    /*
    将matlab中的图像转换为opencv Mat对象指针
    */
    cv::Ptr<cv::Mat> image = ocvMxArrayToImage_uint8(prhs[0]);

    /*
    Sobel
    */
    cv::Mat dx, dy;
    cv::Sobel(*image.get(), dx, -1, 1, 0);
    cv::Sobel(*image.get(), dy, -1, 0, 1);

    /*
    oepncv Mat 转换为matlab中mxArray
    */
    plhs[0] = ocvMxArrayFromMat_uint8(dx);
    plhs[1] = ocvMxArrayFromMat_uint8(dy);

}

matlab测试代码

clear;
clc;

image = imread('F:\\lena\\lena_gray.jpg');
[sobel_dx_img, sobel_dy_img] = compute_sobel(image);

figure(2)
subplot(1,3,1)
imshow(image)
subplot(1,3,2)
imshow(sobel_dx_img)
subplot(1,3,3)
imshow(sobel_dy_img)

image.png

相关文章

网友评论

      本文标题:matlab C++混合编程——opencv

      本文链接:https://www.haomeiwen.com/subject/pdofzqtx.html