I am working on a research project to detect and track hand, then move objects according to hand's motion. I need to calculate the angle between a horizontal axis and the centroid of hand, and update the angle every time the hand move. I implemented code, but it doesn't calculate the angle properly. The output angle has a repeated values i.e (114, -114, 57, 0, -57) and the single value is repeated for several frames, even if i moved my hand.

Here is the code :-

if (dArea > 10000) { //calculate the position of hand int posX = dM10 / dArea; int posY = dM01 / dArea; if (iLastX >= 0 && iLastY >= 0 && posX >= 0 && posY >= 0) { line(imgLines, Point(200, 200), Point(400, 200), Scalar(255), 2, 8, 0); line(imgLines, Point(200, 200), Point(posX, posY), Scalar(0, 0, 255), 2, 8, 0);

```
}
int x1 = 400;
int y1 = 200;
int x2 = posX;
int y2 = posY;
int X = x2 - x1;
int Y = y2 - y1;
int x = pow((double)X, 2); //type casting from int to double
int y = pow((double)Y, 2);
int d = abs(sqrt((double)x + (double)y));
int angleInRadian = atan2(Y,X); //angle in radian
int angleInDegree = angleInRadian * 180 / M_PI; //angle in degree
if (angleInDegree < 0) {
angleInDegree += 2 * M_PI;
}
string Result; // string which will contain the result
ostringstream convert; // stream used for the conversion
convert << angleInDegree; // insert the textual representation of 'Number' in the characters in the stream
Result = convert.str();
putText(imgOriginal, Result, Point2f(iLastX, iLastY), FONT_HERSHEY_PLAIN, 2, Scalar(0, 0, 255, 255));
iLastX = posX;
iLastY = posY;
}
```

- How to calculate the angle properly?
- how to keep only the last line and erase the previous ones?