Skip to content

Instantly share code, notes, and snippets.

@sgarciav
Created May 8, 2018 14:09
Show Gist options
  • Save sgarciav/73ecd74516cb6b93b72bca9ac8698863 to your computer and use it in GitHub Desktop.
Save sgarciav/73ecd74516cb6b93b72bca9ac8698863 to your computer and use it in GitHub Desktop.
Compute major and minor axes of an ellipse from a covariance matrix.
// Taken from http://www.visiondummy.com/2014/04/draw-error-ellipse-representing-covariance-matrix/
// previously defined
cv::Mat covmat;
// Get the eigenvalues and eigenvectors
cv::Mat eigenvalues, eigenvectors;
cv::eigen(covmat, eigenvalues, eigenvectors);
// Calculate the angle between the largest eigenvector and the x-axis
double angle = atan2(eigenvectors.at<double>(0,1), eigenvectors.at<double>(0,0));
//S hift the angle to the [0, 2pi] interval instead of [-pi, pi]
if (angle < 0) {
angle += 2 * M_PI;
}
// Convert to degrees instead of radians
angle = 180 * angle / M_PI;
// Calculate the size of the minor and major axes
double halfmajoraxissize = scale_factor * sqrt(eigenvalues.at<double>(0));
double halfminoraxissize = scale_factor * sqrt(eigenvalues.at<double>(1));
// Return the oriented ellipse
// The -angle is used because OpenCV defines the angle clockwise instead of anti-clockwise
cv::Point2f mean; // need to define
return cv::RotatedRect(mean, cv::Size2f(halfmajoraxissize, halfminoraxissize), -angle);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment