How to implement imgradient () matlab function in opencv android java

I want to use the imgradient() matlab function in my Android application using opencv. how can I do this and which opencv function is equivalent to the matlab imgradient() function.

im using the function below, is this correct?

 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; } 
-1
source share
2 answers

Have you tried using something like sobel or canny ?

0
source

Since matlab imgradient () returns a gradient value (e.g. sqrt (dx (x, y) ² + dy (x, y) ²) for each pixel with x, y coordinates), you can do something like this:

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

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

Hope this helps!

0
source

All Articles