-1

I want to use the imgradient() function of matlab in my android application using opencv. how can i do so and which function of opencv is equivalent to to Matlab imgradient() function.

i m using below mentioned function is it right ?

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;
    }
user1838487
  • 73
  • 1
  • 11

2 Answers2

0

Have you tried using something like sobel or canny operators?

Lorelorelore
  • 3,335
  • 8
  • 29
  • 40
0

As matlab imgradient() returns the gradient "magnitude" (i.e. sqrt(dx(x,y)² + dy(x,y)²) for each pixel with coordinates x,y), you may want to do something like:

// 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));

It should get you what you you want. You can achieve a better performance by accessing gradient data instead of using .at(i,j) for each pixel.

Hope it helps!

Яois
  • 3,838
  • 4
  • 28
  • 50