# Sine or Cosine of every element in Mat (c++)

I was wondering if there is any way to take the sine or cosine of every element in a matrix?

Thanks!

EDIT: For future reference, I did the Taylor expansion of Sine. For pretty good accuracy, I only had to calculate up to the fourth term. However, keep note that if you are trying to estimate sin(pi) or sin(-pi) you have to calculate additional terms (probably 8 total terms).

This link will be useful for those who want to do this: http://en.wikipedia.org/wiki/Taylor_s...

edit retag close merge delete

Actually, you only need to go from -pi/4 to pi/4. For angles between pi/4 and pi/2, you can use the series for cos, substituting (pi/2-x) for your angle. Angles outside this range can be translated into it.

( 2015-02-20 05:52:23 -0500 )edit

Sort by » oldest newest most voted

I haven't found such a function in the API, so I guess you need to loop over the Matrix yourself.

more

This should be the fastest way of retrieving Mat elements

Size contSize = mat.size();
if (mat.isContinous())
{
contSize.width *= contSize.height;
contSize.height = 1;
}
for (int i = 0; i < contSize.height; ++i)
{
T* ptr = mat.ptr<T>(y);
for (int j = 0; j < contSize.width; ++j)
{
ptr[j] = ...;
}
}


according to one of the core developers of OpenCV posted in this topic. Then inside the loop, do apply a sine or cosine on the value based on standard C++ functionality.

more

How precise do you need it?

You can get within a few percent with a third order polynomial. You need to:

1) transfer all matrix values to the range -pi/2 to pi/2 by adding whole multiples of pi. (I assume matrix values are in radians, if they are in degrees multiply by pi/180).

2) calculate Sin(x)=x-(x^3)/6

3) for Cosine calculate Sin(pi/2-x)

if you want better precision you can use higher order polynomials: sin(x) is exactly the infinite polynomial x-(x^3/3!)+(x^5/5!)-(x^7/7!) +.... (look up "Taylor series" for more info) but the accuracy increases pretty fast as you add terms.

I have not tried it, but I guarantee that this would be faster than an element by element sin function (which is probably implemented by a polynomial approximation anyway).

guy

more

1

That's exactly what I ended up doing! Thanks (: +1

( 2015-02-19 09:58:50 -0500 )edit

Could you simply except the question instead of closing it down? We do not close quality solved questions :)

( 2015-02-20 02:08:34 -0500 )edit
1

^^Sorry, I didn't know -.- I will make sure to keep it open!

( 2015-02-20 11:35:31 -0500 )edit

Excuse me . Can I know how to do the first step without any for loop (element by element)?

( 2018-06-24 22:01:13 -0500 )edit

Official site

GitHub

Wiki

Documentation