Given a vector V in 3D space and a normal vector N of a plane, how to calculate the projection of V on the plane?
The following is my C++ and OpenCV implementation of the algorithm.
Vec3d findProjection(Vec3d V, Vec3d N) {
Vec3d v, n;
// We convert both vectors to unit vectors
normalize(V, v);
normalize(N, n);
// Then calculate the cos angle between n and v
double cosVN = v.dot(n);
// Make sure the angle is in range of -90 to 90 degrees
if(cosVN < 0) {
cosVN = -cosVN;
n = -n;
}
double V_len = sqrt(V.dot(V));
double _N_len = V_len * cosVN;
// _N is the projection of V on N
Vec3d _N = _N_len * n;
return V - _N;
}
Vec3d v, n;
// We convert both vectors to unit vectors
normalize(V, v);
normalize(N, n);
// Then calculate the cos angle between n and v
double cosVN = v.dot(n);
// Make sure the angle is in range of -90 to 90 degrees
if(cosVN < 0) {
cosVN = -cosVN;
n = -n;
}
double V_len = sqrt(V.dot(V));
double _N_len = V_len * cosVN;
// _N is the projection of V on N
Vec3d _N = _N_len * n;
return V - _N;
}
没有评论:
发表评论