• Open Source Computer Vision Library

QR分解

Wikipedia,自由的百科全书

  1. #include "stdafx.h"
  2. #include <cxcore.h>
  3. #include <vector>
  4. using namespace std;
  5. #pragma comment(lib,"cxcore.lib")
  6. #pragma comment(lib,"highgui.lib")
  7. void cvQR(CvMat *inputA,CvMat *q,CvMat *r)
  8. {
  9.  
  10.  
  11. CvSize inputSize=cvGetSize(inputA);
  12. int width=inputSize.width;
  13. int height=inputSize.height;
  14. cvSetIdentity(q);
  15. cvCopy(inputA,r);
  16. vector<CvMat **> matMem;
  17. CvMat *tempH=cvCreateMat(height,height,CV_32FC1);
  18. matMem.push_back(&tempH);
  19. CvMat *v=cvCreateMat(height,1,CV_32FC1);
  20. matMem.push_back(&v);
  21. CvMat *tempCol=cvCreateMat(height,1,CV_32FC1);
  22. matMem.push_back(&tempCol);
  23. CvMat *tempCol2=cvCreateMat(height,1,CV_32FC1);
  24. matMem.push_back(&tempCol2);
  25. CvMat *iMat=cvCreateMat(height,height,CV_32FC1);
  26. matMem.push_back(&iMat);
  27. CvMat *transV=cvCreateMat(1,height,CV_32FC1);
  28. matMem.push_back(&transV);
  29.  
  30. for (int i=0; i<width; i++)
  31. {
  32. float b[] = {0};
  33. CvMat temp;
  34. cvGetCol(r,&temp,i); //get the i col
  35. cvCopy(&temp,tempCol); //copy the row,don't hurt the original column
  36. cvGetSubRect(tempCol,&temp,cvRect(0,0,1,i)); //get the header
  37. if (temp.rows == 0 || temp.cols == 0)
  38. memcpy(temp.data.fl,b,sizeof(float));
  39. else
  40. cvZero(&temp); //make it zero
  41. float colNorm=cvNorm(tempCol); //get the norm of the current column
  42. cvZero(tempCol2); //zero the e vector
  43. float tempval=cvGet2D(r,i,i).val[0];
  44. cvSet2D(tempCol2,i,0,cvScalar(tempval>0?-1:1*colNorm,0,0)); //set the new value
  45. cvSub(tempCol,tempCol2,v); //subtract the two vectors,get v
  46.  
  47. float val2=cvNorm(v);
  48. if (val2==0)
  49. {
  50. continue;
  51. }
  52. val2*=val2;
  53. val2=1/val2;
  54. cvTranspose(v,transV);
  55. cvMatMul(v,transV,tempH); //
  56. cvScale(tempH,tempH,2*val2);
  57. cvSetIdentity(iMat); //the identity matrix
  58. cvSub(iMat,tempH,iMat);
  59. cvCopy(iMat,tempH); //get the H matrix
  60. cvTranspose(tempH,tempH); //transpose
  61. cvMatMul(q,tempH,q); //q=q.h
  62. cvGetCol(r,&temp,i); //get the col again
  63. cvSet2D(&temp,i,0,cvScalar(colNorm,0,0)); //set the norm
  64. cvGetSubRect(r,&temp,cvRect(i,i+1,1,height-i-1));
  65. if (temp.rows == 0 || temp.cols == 0)
  66. memcpy(temp.data.fl,b,sizeof(float));
  67. else
  68. cvZero(&temp); //zero the submatrix
  69. }
  70.  
  71. for (int j=0; j<matMem.size(); j++)
  72. {
  73. cvReleaseMat(matMem[j]);
  74. }
  75.  
  76. }
  77.  
  78. int main(int argc, char* argv[]){
  79. float matData[]={1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7};
  80. float rData[16];
  81. float qData[16];
  82. CvMat aMat=cvMat(4,4,CV_32FC1,matData);
  83. CvMat rMat=cvMat(4,4,CV_32FC1,rData);
  84. CvMat qMat=cvMat(4,4,CV_32FC1,qData);
  85. cvQR(&aMat,&qMat,&rMat);
  86. float det=cvDet(&qMat); return 0;
  87. }
  88.  
Views
Personal tools