Ask Your Question
0

Computing gradient direction of image

asked 2014-10-15 03:14:56 -0500

tarmizi_adam2005 gravatar image

Hi,

I am trying to calculate the gradient direction of an image.

I tried the following function:

Mat computeArcTan(Mat &dst1, Mat &dst2)
{
   Mat angle;//(dst1.rows,dst1.cols,CV_32F);
   ofstream myFile("angle.csv");
   const double pi = 3.14159;

   for(int row = 0; row < dst1.rows; row++)
   {
       for(int col = 0; col < dst1.cols; col++ )
       {
           //angle.at<uchar>(row,col)=(double)atan2(dst1.at<uchar>(row,col),dst2.at<uchar>(row,col)*180/pi);
           angle.push_back((double)atan2(dst1.at<uchar>(row,col),dst2.at<uchar>(row,col))*180/pi);
           myFile << angle.at<double>(row,col) <<",";
       }

            myFile << endl;
   }
   return angle;
}

the dst1 and dst2 are the gradient of x and y direction. However, I believe I am not getting the correct direction values. The values printed in the csv file is a repetition of values of 0, 18.435, 45 and 71.3872. When i checked with matlab, it is totally wrong. I know openCV has the function cartToPolar() but I'm trying to hard code it just to understand the process behind it.

Any Ideas or direction/suggestion on what am i doing wrong ?

thanks,

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
2

answered 2014-10-15 07:11:03 -0500

rwong gravatar image

Some possibilities.


Firstly, when using the Mat.at<T>() operator, you have the responsibility to make sure that T corresponds to the actual data type of the matrix. If the data types do not match, it is an undefined behavior - it is effectively an invalid type cast and will eventually cause your program to crash. The Mat.at<T>() operator does not perform type value conversion.

For example:

  • For CV_8UC1 use uchar
  • For CV_8UC3 use cv::Vec3b
  • For CV_32FC1 use float
  • For CV_32SC1 use int32_t

Secondly, keep in mind that the atan2(y, x) function is traditionally defined with rise (y) as the first argument, and run (x) as the second argument. This comes from the phrase "Rise over Run" in the definition of slope.

edit flag offensive delete link more

Comments

Hi rwong,

Thank you very much for your reply and suggestions. I understand it now. After making some changes as you suggested I have managed to correct the problems. Thank again.

tarmizi_adam2005 gravatar imagetarmizi_adam2005 ( 2014-10-16 02:12:57 -0500 )edit

Question Tools

Stats

Asked: 2014-10-15 03:14:56 -0500

Seen: 580 times

Last updated: Oct 15 '14