简介
本篇主要是对opnecv函数cvSolve的熟悉笔记。这里只是简单用它来拟合抛物线。
大致内容为:预先设定三个点,用这三个点来拟合出它们的抛物线。
具体实现
实现代码
#include <opencv2/opencv.hpp>
#include <stdio.h>
using namespace cv;
using namespace std;
#define pointNUmber 3
Mat src;
CvPoint point[pointNUmber];
int width, height;
int pointAddr[pointNUmber][2] = {{70, 420}, {160, 90}, {390, 410}};
float A[3][3] = {{70*70, 70, 1}, {160*160, 160, 1}, {390*390, 390, 1}};
float B[3] = {420, 90, 410};
float C[3] = {0, 0, 0};
CvMat* matA = cvCreateMat(3,3,CV_32FC1);
CvMat* matB = cvCreateMat(3,1,CV_32FC1);
CvMat* matC = cvCreateMat(3,1,CV_32FC1);
void Init(void){
IplImage ip1;
CvScalar s;
int i;
src = Mat(480, 480, CV_8UC1, Scalar(0,0,0));
ip1 = src;
width = ip1.width;
height = ip1.height;
for(i=0; i<pointNUmber; i++){
point[i].x = pointAddr[i][0];
point[i].y = pointAddr[i][1];
s.val[0] = 255;
circle(src, point[i], 3, cvScalar(255,255,255), -1);
}
imshow("src", src);
}
void work(void){
int i;
cvSetData(matA, A, CV_AUTOSTEP);
cvSetData(matB, B, CV_AUTOSTEP);
cvSolve(matA, matB, matC, CV_LU);
for(i=0;i<3;i++){
printf("%f\t", matC->data.fl[i]);
}
}
void show(void){
int i, j;
int result;
CvScalar s;
for(i=0; i<width; i++){
result = (int)(i*i*matC->data.fl[0]) + i*matC->data.fl[1] + matC->data.fl[2];
s.val[0] = 255;
if(result < height){
circle(src, cvPoint(i, result), 3, cvScalar(255,255,255), -1);
}
}
imshow("dst", src);
}
int main(int argc, char* argv[]){
int k;
Init();
work();
show();
waitKey(0);
return 0;
}
代码讲解
1、初始化一副480X480的空白图片,接着以预先设置的三个点:{70, 420}, {160, 90}, {390, 410}为圆心,在该图片上显示出这些点。
void Init(void){
IplImage ip1;
CvScalar s;
int i;
src = Mat(480, 480, CV_8UC1, Scalar(0,0,0));
ip1 = src;
width = ip1.width;
height = ip1.height;
for(i=0; i<pointNUmber; i++){
point[i].x = pointAddr[i][0];
point[i].y = pointAddr[i][1];
s.val[0] = 255;
circle(src, point[i], 3, cvScalar(255,255,255), -1);
}
imshow("src", src);
}
2、根据公司a*x1*x1 + b*x1 + c = y1,a*x2*x2 + b*x2 + c = y2,a*x3*x3 + b*x3 + c = y3。其中x1、x2、x3为那三个点的X坐标;
y1、y2、y3为那三个点的Y坐标;a、b、c为被拟合的抛物线参数。
填充矩阵:A[3][3] = [[x1*x1, x1, 1], [x2*x2, x2, 1], [x3*x3, x3, 1]]
B[3] = [y1, y2, y3];
将矩阵A、B作为输入参数,生成抛物线参数a、b、c,保存到matC中。
void work(void){
int i;
cvSetData(matA, A, CV_AUTOSTEP);
cvSetData(matB, B, CV_AUTOSTEP);
cvSolve(matA, matB, matC, CV_LU);
for(i=0;i<3;i++){
printf("%f\t", matC->data.fl[i]);
}
}
3、根据计算得到的抛物线参数,拟合出抛物线,并在之前的空白图片上显示出来:
void show(void){
int i, j;
int result;
CvScalar s;
for(i=0; i<width; i++){
result = (int)(i*i*matC->data.fl[0]) + i*matC->data.fl[1] + matC->data.fl[2];
s.val[0] = 255;
if(result < height){
circle(src, cvPoint(i, result), 3, cvScalar(255,255,255), -1);
}
}
imshow("dst", src);
}
结果显示
对应的效果演示如下:
参考资料
http://blog.csdn.net/woxincd/article/details/7278019