我使用OpenCV实现了面部跟踪的卡尔曼滤波器。但效果并不符合我的预期:跟踪盒延迟很多(跟踪盒非常缓慢地移动到我脸上)。以下是我的代码。我是以正确的方式实施的吗?
#include "opencv2/opencv.hpp"
using namespace cv;
using namespace std;
int main()
{
// detect face
CascadeClassifier cc("model/haarcascade_frontalface_alt2.xml");
VideoCapture vc(0);
Mat frame;
Rect face;
// intialization of KF...
KalmanFilter KF(4, 2, 0);
KF.transitionMatrix = *(Mat_<float>(4, 4) << 1,0,1,0, 0,1,0,1, 0,0,1,0, 0,0,0,1);
Mat_<float> measurement(2,1); measurement.setTo(Scalar(0));
setIdentity(KF.measurementMatrix);
setIdentity(KF.processNoiseCov, Scalar::all(1e-4));
setIdentity(KF.measurementNoiseCov, Scalar::all(10));
setIdentity(KF.errorCovPost, Scalar::all(.1));
for(; ;) {
vc >> frame;
vector<Rect> faces;
cc.detectMultiScale(frame, faces, 1.2, 3, CASCADE_DO_ROUGH_SEARCH, Size(80, 80));
if (faces.size() > 0) {
face = faces[0];
KF.statePre.at<float>(0) = face.x;
KF.statePre.at<float>(1) = face.y;
KF.statePre.at<float>(2) = 0;
KF.statePre.at<float>(3) = 0;
}
// First predict, to update the internal statePre variable
Mat prediction = KF.predict();
Rect predictFace((int)prediction.at<float>(0), (int)prediction.at<float>(1), face.width, face.height);
// The update phase
measurement(0) = face.x;
measurement(1) = face.y;
Mat estimated = KF.correct(measurement);
Rect estFace((int)estimated.at<float>(0), (int)estimated.at<float>(1), face.width, face.height);
rectangle(frame, predictFace, Scalar(0, 255, 0));
rectangle(frame, estFace, Scalar(0, 0, 255));
imshow("", frame);
waitKey(50);
}
return 0;
}