【问题标题】:how to implement imgradient() function of matlab in opencv android java如何在opencv android java中实现matlab的imgradient()函数
【发布时间】:2014-05-28 01:21:23
【问题描述】:

我想使用opencv.在我的android应用程序中使用matlabimgradient()函数,我该怎么做以及opencv的哪个函数相当于Matlab imgradient()函数。

我使用下面提到的功能对吗?

public Mat imgradient(Mat grayScaleImage)
    {
        Mat grad_x=new Mat();
        Mat grad_y = new Mat();
        Mat abs_grad_x=new Mat();
        Mat abs_grad_y=new Mat();            
        Mat gradientImag = new Mat(grayScaleImage.rows(),grayScaleImage.cols(),CvType.CV_8UC1);

         Imgproc.Sobel(grayScaleImage, grad_x, CvType.CV_16S, 1, 0,3,1,0,Imgproc.BORDER_DEFAULT );
         Core.convertScaleAbs( grad_x, abs_grad_x );             
         Imgproc.Sobel( grayScaleImage, grad_y, CvType.CV_16S, 0, 1, 3, 1,0,Imgproc.BORDER_DEFAULT );
         Core.convertScaleAbs( grad_y, abs_grad_y );                
         double[] buff_grad = new double[1];
         for(int i = 0; i < abs_grad_y.cols(); i++)
            {
                for(int j =0 ; j<abs_grad_y.rows() ; j++)
                {
                    double[] buff_x = abs_grad_x.get(j, i);
                    double[] buff_y = abs_grad_y.get(j, i);
                    double x =  buff_x[0];
                    double y =  buff_y[0];
                    double ans=0;
                    try
                    {
                         ans = Math.sqrt(Math.pow(x,2)+Math.pow(y,2));
                    }catch(NullPointerException e)
                    {
                        ans = 0;

                    }
                    buff_grad[0] =  ans;                        
                    gradientImag.put(j, i, buff_grad);   
                }
            }           
        return gradientImag;
    }

【问题讨论】:

    标签: java android matlab opencv


    【解决方案1】:

    由于 matlab imgradient() 返回具有坐标 x,y 的每个像素的梯度“幅度”(即 sqrt(dx(x,y)² + dy(x,y)²)),您可能想要做一些事情喜欢:

    // 1) Get the horizontal gradient
    Mat kH = (cv::Mat_<double>(1,3) << -1,0,1); // differential kernel in x
    Mat Dx;
    filter2D(image, Dx, -1, kH, cv::Point(-1,-1), 0);
    
    // 2) Get the vertical gradient
    Mat kV = (cv::Mat_<double>(3,1) << -1,0,1); // differential kernel in y
    Mat Dy;
    filter2D(image, Dy, -1, kV, cv::Point(-1,-1), 0);
    
    // 3) Get sqrt(dx²+dy²) in each point
    for(int i=0; i<Dx.rows; i++)
        for(int j=0; j<Dx.cols; j++)
            Dmag.at<double>(i,j) = sqrt(pow(Dx.at<double>(i,j),2)+pow(Dy.at<double>(i,j),2));
    

    它应该可以得到你想要的。您可以通过访问梯度数据而不是对每个像素使用 .at(i,j) 来获得更好的性能。

    希望对您有所帮助!

    【讨论】:

    • 我已经添加了我在问题中使用的功能
    【解决方案2】:

    您是否尝试过使用类似sobelcanny 的运算符?

    【讨论】:

    • 我已经添加了我在问题中使用的功能
    猜你喜欢
    • 1970-01-01
    • 2013-07-13
    • 2014-03-30
    • 1970-01-01
    • 2015-01-29
    • 2015-11-28
    • 2015-07-24
    • 2018-05-29
    • 2014-06-21
    相关资源
    最近更新 更多