2 * Copyright (c) 2011. Philipp Wagner <bytefish[at]gmx[dot]de>.
3 * Released to public domain under terms of the BSD Simplified license.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the organization nor the names of its contributors
13 * may be used to endorse or promote products derived from this software
14 * without specific prior written permission.
16 * See <http://www.opensource.org/licenses/bsd-license>
19 #include "precomp.hpp"
27 // Removes duplicate elements in a given vector.
28 template<typename _Tp>
29 inline std::vector<_Tp> remove_dups(const std::vector<_Tp>& src) {
30 typedef typename std::set<_Tp>::const_iterator constSetIterator;
31 typedef typename std::vector<_Tp>::const_iterator constVecIterator;
32 std::set<_Tp> set_elems;
33 for (constVecIterator it = src.begin(); it != src.end(); ++it)
34 set_elems.insert(*it);
35 std::vector<_Tp> elems;
36 for (constSetIterator it = set_elems.begin(); it != set_elems.end(); ++it)
41 static Mat argsort(InputArray _src, bool ascending=true)
43 Mat src = _src.getMat();
44 if (src.rows != 1 && src.cols != 1) {
45 String error_message = "Wrong shape of input matrix! Expected a matrix with one row or column.";
46 CV_Error(Error::StsBadArg, error_message);
48 int flags = SORT_EVERY_ROW | (ascending ? SORT_ASCENDING : SORT_DESCENDING);
50 sortIdx(src.reshape(1,1),sorted_indices,flags);
51 return sorted_indices;
54 static Mat asRowMatrix(InputArrayOfArrays src, int rtype, double alpha=1, double beta=0) {
55 // make sure the input data is a vector of matrices or vector of vector
56 if(src.kind() != _InputArray::STD_VECTOR_MAT && src.kind() != _InputArray::STD_VECTOR_VECTOR) {
57 String error_message = "The data is expected as InputArray::STD_VECTOR_MAT (a std::vector<Mat>) or _InputArray::STD_VECTOR_VECTOR (a std::vector< std::vector<...> >).";
58 CV_Error(Error::StsBadArg, error_message);
61 size_t n = src.total();
62 // return empty matrix if no matrices given
65 // dimensionality of (reshaped) samples
66 size_t d = src.getMat(0).total();
68 Mat data((int)n, (int)d, rtype);
70 for(int i = 0; i < (int)n; i++) {
71 // make sure data can be reshaped, throw exception if not!
72 if(src.getMat(i).total() != d) {
73 String error_message = format("Wrong number of elements in matrix #%d! Expected %d was %d.", i, (int)d, (int)src.getMat(i).total());
74 CV_Error(Error::StsBadArg, error_message);
76 // get a hold of the current row
78 // make reshape happy by cloning for non-continuous matrices
79 if(src.getMat(i).isContinuous()) {
80 src.getMat(i).reshape(1, 1).convertTo(xi, rtype, alpha, beta);
82 src.getMat(i).clone().reshape(1, 1).convertTo(xi, rtype, alpha, beta);
88 static void sortMatrixColumnsByIndices(InputArray _src, InputArray _indices, OutputArray _dst) {
89 if(_indices.getMat().type() != CV_32SC1) {
90 CV_Error(Error::StsUnsupportedFormat, "cv::sortColumnsByIndices only works on integer indices!");
92 Mat src = _src.getMat();
93 std::vector<int> indices = _indices.getMat();
94 _dst.create(src.rows, src.cols, src.type());
95 Mat dst = _dst.getMat();
96 for(size_t idx = 0; idx < indices.size(); idx++) {
97 Mat originalCol = src.col(indices[idx]);
98 Mat sortedCol = dst.col((int)idx);
99 originalCol.copyTo(sortedCol);
103 static Mat sortMatrixColumnsByIndices(InputArray src, InputArray indices) {
105 sortMatrixColumnsByIndices(src, indices, dst);
110 template<typename _Tp> static bool
111 isSymmetric_(InputArray src) {
112 Mat _src = src.getMat();
113 if(_src.cols != _src.rows)
115 for (int i = 0; i < _src.rows; i++) {
116 for (int j = 0; j < _src.cols; j++) {
117 _Tp a = _src.at<_Tp> (i, j);
118 _Tp b = _src.at<_Tp> (j, i);
127 template<typename _Tp> static bool
128 isSymmetric_(InputArray src, double eps) {
129 Mat _src = src.getMat();
130 if(_src.cols != _src.rows)
132 for (int i = 0; i < _src.rows; i++) {
133 for (int j = 0; j < _src.cols; j++) {
134 _Tp a = _src.at<_Tp> (i, j);
135 _Tp b = _src.at<_Tp> (j, i);
136 if (std::abs(a - b) > eps) {
144 static bool isSymmetric(InputArray src, double eps=1e-16)
146 Mat m = src.getMat();
148 case CV_8SC1: return isSymmetric_<char>(m); break;
150 return isSymmetric_<unsigned char>(m); break;
152 return isSymmetric_<short>(m); break;
154 return isSymmetric_<unsigned short>(m); break;
156 return isSymmetric_<int>(m); break;
158 return isSymmetric_<float>(m, eps); break;
160 return isSymmetric_<double>(m, eps); break;
168 //------------------------------------------------------------------------------
169 // cv::subspaceProject
170 //------------------------------------------------------------------------------
171 Mat subspaceProject(InputArray _W, InputArray _mean, InputArray _src) {
174 Mat mean = _mean.getMat();
175 Mat src = _src.getMat();
176 // get number of samples and dimension
179 // make sure the data has the correct shape
181 String error_message = format("Wrong shapes for given matrices. Was size(src) = (%d,%d), size(W) = (%d,%d).", src.rows, src.cols, W.rows, W.cols);
182 CV_Error(Error::StsBadArg, error_message);
184 // make sure mean is correct if not empty
185 if(!mean.empty() && (mean.total() != (size_t) d)) {
186 String error_message = format("Wrong mean shape for the given data matrix. Expected %d, but was %d.", d, mean.total());
187 CV_Error(Error::StsBadArg, error_message);
189 // create temporary matrices
191 // make sure you operate on correct type
192 src.convertTo(X, W.type());
193 // safe to do, because of above assertion
195 for(int i=0; i<n; i++) {
197 subtract(r_i, mean.reshape(1,1), r_i);
200 // finally calculate projection as Y = (X-mean)*W
201 gemm(X, W, 1.0, Mat(), 0.0, Y);
205 //------------------------------------------------------------------------------
206 // cv::subspaceReconstruct
207 //------------------------------------------------------------------------------
208 Mat subspaceReconstruct(InputArray _W, InputArray _mean, InputArray _src)
212 Mat mean = _mean.getMat();
213 Mat src = _src.getMat();
214 // get number of samples and dimension
217 // make sure the data has the correct shape
219 String error_message = format("Wrong shapes for given matrices. Was size(src) = (%d,%d), size(W) = (%d,%d).", src.rows, src.cols, W.rows, W.cols);
220 CV_Error(Error::StsBadArg, error_message);
222 // make sure mean is correct if not empty
223 if(!mean.empty() && (mean.total() != (size_t) W.rows)) {
224 String error_message = format("Wrong mean shape for the given eigenvector matrix. Expected %d, but was %d.", W.cols, mean.total());
225 CV_Error(Error::StsBadArg, error_message);
227 // initialize temporary matrices
229 // copy data & make sure we are using the correct type
230 src.convertTo(Y, W.type());
231 // calculate the reconstruction
232 gemm(Y, W, 1.0, Mat(), 0.0, X, GEMM_2_T);
233 // safe to do because of above assertion
235 for(int i=0; i<n; i++) {
237 add(r_i, mean.reshape(1,1), r_i);
244 class EigenvalueDecomposition {
247 // Holds the data dimension.
250 // Stores real/imag part of a complex division.
253 // Pointer to internal memory.
257 // Holds the computed eigenvalues.
260 // Holds the computed eigenvectors.
264 template<typename _Tp>
265 _Tp *alloc_1d(int m) {
270 template<typename _Tp>
271 _Tp *alloc_1d(int m, _Tp val) {
272 _Tp *arr = alloc_1d<_Tp> (m);
273 for (int i = 0; i < m; i++)
279 template<typename _Tp>
280 _Tp **alloc_2d(int m, int _n) {
281 _Tp **arr = new _Tp*[m];
282 for (int i = 0; i < m; i++)
283 arr[i] = new _Tp[_n];
288 template<typename _Tp>
289 _Tp **alloc_2d(int m, int _n, _Tp val) {
290 _Tp **arr = alloc_2d<_Tp> (m, _n);
291 for (int i = 0; i < m; i++) {
292 for (int j = 0; j < _n; j++) {
299 void cdiv(double xr, double xi, double yr, double yi) {
301 if (std::abs(yr) > std::abs(yi)) {
304 cdivr = (xr + r * xi) / dv;
305 cdivi = (xi - r * xr) / dv;
309 cdivr = (r * xr + xi) / dv;
310 cdivi = (r * xi - xr) / dv;
314 // Nonsymmetric reduction from Hessenberg to real Schur form.
318 // This is derived from the Algol procedure hqr2,
319 // by Martin and Wilkinson, Handbook for Auto. Comp.,
320 // Vol.ii-Linear Algebra, and the corresponding
321 // Fortran subroutine in EISPACK.
328 double eps = std::pow(2.0, -52.0);
329 double exshift = 0.0;
330 double p = 0, q = 0, r = 0, s = 0, z = 0, t, w, x, y;
332 // Store roots isolated by balanc and compute matrix norm
335 for (int i = 0; i < nn; i++) {
336 if (i < low || i > high) {
340 for (int j = std::max(i - 1, 0); j < nn; j++) {
341 norm = norm + std::abs(H[i][j]);
345 // Outer loop over eigenvalue index
349 // Look for single small sub-diagonal element
352 s = std::abs(H[l - 1][l - 1]) + std::abs(H[l][l]);
356 if (std::abs(H[l][l - 1]) < eps * s) {
362 // Check for convergence
366 H[n1][n1] = H[n1][n1] + exshift;
374 } else if (l == n1 - 1) {
375 w = H[n1][n1 - 1] * H[n1 - 1][n1];
376 p = (H[n1 - 1][n1 - 1] - H[n1][n1]) / 2.0;
378 z = std::sqrt(std::abs(q));
379 H[n1][n1] = H[n1][n1] + exshift;
380 H[n1 - 1][n1 - 1] = H[n1 - 1][n1 - 1] + exshift;
399 s = std::abs(x) + std::abs(z);
402 r = std::sqrt(p * p + q * q);
408 for (int j = n1 - 1; j < nn; j++) {
410 H[n1 - 1][j] = q * z + p * H[n1][j];
411 H[n1][j] = q * H[n1][j] - p * z;
414 // Column modification
416 for (int i = 0; i <= n1; i++) {
418 H[i][n1 - 1] = q * z + p * H[i][n1];
419 H[i][n1] = q * H[i][n1] - p * z;
422 // Accumulate transformations
424 for (int i = low; i <= high; i++) {
426 V[i][n1 - 1] = q * z + p * V[i][n1];
427 V[i][n1] = q * V[i][n1] - p * z;
441 // No convergence yet
451 y = H[n1 - 1][n1 - 1];
452 w = H[n1][n1 - 1] * H[n1 - 1][n1];
455 // Wilkinson's original ad hoc shift
459 for (int i = low; i <= n1; i++) {
462 s = std::abs(H[n1][n1 - 1]) + std::abs(H[n1 - 1][n1 - 2]);
467 // MATLAB's new ad hoc shift
477 s = x - w / ((y - x) / 2.0 + s);
478 for (int i = low; i <= n1; i++) {
486 iter = iter + 1; // (Could check iteration count here.)
488 // Look for two consecutive small sub-diagonal elements
494 p = (r * s - w) / H[m + 1][m] + H[m][m + 1];
495 q = H[m + 1][m + 1] - z - r - s;
497 s = std::abs(p) + std::abs(q) + std::abs(r);
504 if (std::abs(H[m][m - 1]) * (std::abs(q) + std::abs(r)) < eps * (std::abs(p)
505 * (std::abs(H[m - 1][m - 1]) + std::abs(z) + std::abs(
506 H[m + 1][m + 1])))) {
512 for (int i = m + 2; i <= n1; i++) {
519 // Double QR step involving rows l:n and columns m:n
521 for (int k = m; k <= n1 - 1; k++) {
522 bool notlast = (k != n1 - 1);
526 r = (notlast ? H[k + 2][k - 1] : 0.0);
527 x = std::abs(p) + std::abs(q) + std::abs(r);
537 s = std::sqrt(p * p + q * q + r * r);
543 H[k][k - 1] = -s * x;
545 H[k][k - 1] = -H[k][k - 1];
556 for (int j = k; j < nn; j++) {
557 p = H[k][j] + q * H[k + 1][j];
559 p = p + r * H[k + 2][j];
560 H[k + 2][j] = H[k + 2][j] - p * z;
562 H[k][j] = H[k][j] - p * x;
563 H[k + 1][j] = H[k + 1][j] - p * y;
566 // Column modification
568 for (int i = 0; i <= std::min(n1, k + 3); i++) {
569 p = x * H[i][k] + y * H[i][k + 1];
571 p = p + z * H[i][k + 2];
572 H[i][k + 2] = H[i][k + 2] - p * r;
574 H[i][k] = H[i][k] - p;
575 H[i][k + 1] = H[i][k + 1] - p * q;
578 // Accumulate transformations
580 for (int i = low; i <= high; i++) {
581 p = x * V[i][k] + y * V[i][k + 1];
583 p = p + z * V[i][k + 2];
584 V[i][k + 2] = V[i][k + 2] - p * r;
586 V[i][k] = V[i][k] - p;
587 V[i][k + 1] = V[i][k + 1] - p * q;
591 } // check convergence
592 } // while (n1 >= low)
594 // Backsubstitute to find vectors of upper triangular form
600 for (n1 = nn - 1; n1 >= 0; n1--) {
609 for (int i = n1 - 1; i >= 0; i--) {
612 for (int j = l; j <= n1; j++) {
613 r = r + H[i][j] * H[j][n1];
624 H[i][n1] = -r / (eps * norm);
627 // Solve real equations
632 q = (d[i] - p) * (d[i] - p) + e[i] * e[i];
633 t = (x * s - z * r) / q;
635 if (std::abs(x) > std::abs(z)) {
636 H[i + 1][n1] = (-r - w * t) / x;
638 H[i + 1][n1] = (-s - y * t) / z;
644 t = std::abs(H[i][n1]);
645 if ((eps * t) * t > 1) {
646 for (int j = i; j <= n1; j++) {
647 H[j][n1] = H[j][n1] / t;
656 // Last vector component imaginary so matrix is triangular
658 if (std::abs(H[n1][n1 - 1]) > std::abs(H[n1 - 1][n1])) {
659 H[n1 - 1][n1 - 1] = q / H[n1][n1 - 1];
660 H[n1 - 1][n1] = -(H[n1][n1] - p) / H[n1][n1 - 1];
662 cdiv(0.0, -H[n1 - 1][n1], H[n1 - 1][n1 - 1] - p, q);
663 H[n1 - 1][n1 - 1] = cdivr;
664 H[n1 - 1][n1] = cdivi;
668 for (int i = n1 - 2; i >= 0; i--) {
669 double ra, sa, vr, vi;
672 for (int j = l; j <= n1; j++) {
673 ra = ra + H[i][j] * H[j][n1 - 1];
674 sa = sa + H[i][j] * H[j][n1];
685 cdiv(-ra, -sa, w, q);
686 H[i][n1 - 1] = cdivr;
690 // Solve complex equations
694 vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q;
695 vi = (d[i] - p) * 2.0 * q;
696 if (vr == 0.0 && vi == 0.0) {
697 vr = eps * norm * (std::abs(w) + std::abs(q) + std::abs(x)
698 + std::abs(y) + std::abs(z));
700 cdiv(x * r - z * ra + q * sa,
701 x * s - z * sa - q * ra, vr, vi);
702 H[i][n1 - 1] = cdivr;
704 if (std::abs(x) > (std::abs(z) + std::abs(q))) {
705 H[i + 1][n1 - 1] = (-ra - w * H[i][n1 - 1] + q
707 H[i + 1][n1] = (-sa - w * H[i][n1] - q * H[i][n1
710 cdiv(-r - y * H[i][n1 - 1], -s - y * H[i][n1], z,
712 H[i + 1][n1 - 1] = cdivr;
713 H[i + 1][n1] = cdivi;
719 t = std::max(std::abs(H[i][n1 - 1]), std::abs(H[i][n1]));
720 if ((eps * t) * t > 1) {
721 for (int j = i; j <= n1; j++) {
722 H[j][n1 - 1] = H[j][n1 - 1] / t;
723 H[j][n1] = H[j][n1] / t;
731 // Vectors of isolated roots
733 for (int i = 0; i < nn; i++) {
734 if (i < low || i > high) {
735 for (int j = i; j < nn; j++) {
741 // Back transformation to get eigenvectors of original matrix
743 for (int j = nn - 1; j >= low; j--) {
744 for (int i = low; i <= high; i++) {
746 for (int k = low; k <= std::min(j, high); k++) {
747 z = z + V[i][k] * H[k][j];
754 // Nonsymmetric reduction to Hessenberg form.
756 // This is derived from the Algol procedures orthes and ortran,
757 // by Martin and Wilkinson, Handbook for Auto. Comp.,
758 // Vol.ii-Linear Algebra, and the corresponding
759 // Fortran subroutines in EISPACK.
763 for (int m = low + 1; m <= high - 1; m++) {
768 for (int i = m; i <= high; i++) {
769 scale = scale + std::abs(H[i][m - 1]);
773 // Compute Householder transformation.
776 for (int i = high; i >= m; i--) {
777 ort[i] = H[i][m - 1] / scale;
778 h += ort[i] * ort[i];
780 double g = std::sqrt(h);
787 // Apply Householder similarity transformation
788 // H = (I-u*u'/h)*H*(I-u*u')/h)
790 for (int j = m; j < n; j++) {
792 for (int i = high; i >= m; i--) {
793 f += ort[i] * H[i][j];
796 for (int i = m; i <= high; i++) {
797 H[i][j] -= f * ort[i];
801 for (int i = 0; i <= high; i++) {
803 for (int j = high; j >= m; j--) {
804 f += ort[j] * H[i][j];
807 for (int j = m; j <= high; j++) {
808 H[i][j] -= f * ort[j];
811 ort[m] = scale * ort[m];
812 H[m][m - 1] = scale * g;
816 // Accumulate transformations (Algol's ortran).
818 for (int i = 0; i < n; i++) {
819 for (int j = 0; j < n; j++) {
820 V[i][j] = (i == j ? 1.0 : 0.0);
824 for (int m = high - 1; m >= low + 1; m--) {
825 if (H[m][m - 1] != 0.0) {
826 for (int i = m + 1; i <= high; i++) {
827 ort[i] = H[i][m - 1];
829 for (int j = m; j <= high; j++) {
831 for (int i = m; i <= high; i++) {
832 g += ort[i] * V[i][j];
834 // Double division avoids possible underflow
835 g = (g / ort[m]) / H[m][m - 1];
836 for (int i = m; i <= high; i++) {
837 V[i][j] += g * ort[i];
844 // Releases all internal working memory.
846 // releases the working data
850 for (int i = 0; i < n; i++) {
858 // Computes the Eigenvalue Decomposition for a matrix given in H.
860 // Allocate memory for the working data.
861 V = alloc_2d<double> (n, n, 0.0);
862 d = alloc_1d<double> (n);
863 e = alloc_1d<double> (n);
864 ort = alloc_1d<double> (n);
865 // Reduce to Hessenberg form.
867 // Reduce Hessenberg to real Schur form.
869 // Copy eigenvalues to OpenCV Matrix.
870 _eigenvalues.create(1, n, CV_64FC1);
871 for (int i = 0; i < n; i++) {
872 _eigenvalues.at<double> (0, i) = d[i];
874 // Copy eigenvectors to OpenCV Matrix.
875 _eigenvectors.create(n, n, CV_64FC1);
876 for (int i = 0; i < n; i++)
877 for (int j = 0; j < n; j++)
878 _eigenvectors.at<double> (i, j) = V[i][j];
879 // Deallocate the memory by releasing all internal working data.
884 EigenvalueDecomposition()
887 // Initializes & computes the Eigenvalue Decomposition for a general matrix
888 // given in src. This function is a port of the EigenvalueSolver in JAMA,
889 // which has been released to public domain by The MathWorks and the
890 // National Institute of Standards and Technology (NIST).
891 EigenvalueDecomposition(InputArray src) {
895 // This function computes the Eigenvalue Decomposition for a general matrix
896 // given in src. This function is a port of the EigenvalueSolver in JAMA,
897 // which has been released to public domain by The MathWorks and the
898 // National Institute of Standards and Technology (NIST).
899 void compute(InputArray src)
901 if(isSymmetric(src)) {
902 // Fall back to OpenCV for a symmetric matrix!
903 cv::eigen(src, _eigenvalues, _eigenvectors);
906 // Convert the given input matrix to double. Is there any way to
907 // prevent allocating the temporary memory? Only used for copying
908 // into working memory and deallocated after.
909 src.getMat().convertTo(tmp, CV_64FC1);
910 // Get dimension of the matrix.
912 // Allocate the matrix data to work on.
913 this->H = alloc_2d<double> (n, n);
914 // Now safely copy the data.
915 for (int i = 0; i < tmp.rows; i++) {
916 for (int j = 0; j < tmp.cols; j++) {
917 this->H[i][j] = tmp.at<double>(i, j);
920 // Deallocates the temporary matrix before computing.
922 // Performs the eigenvalue decomposition of H.
927 ~EigenvalueDecomposition() {}
929 // Returns the eigenvalues of the Eigenvalue Decomposition.
930 Mat eigenvalues() { return _eigenvalues; }
931 // Returns the eigenvectors of the Eigenvalue Decomposition.
932 Mat eigenvectors() { return _eigenvectors; }
936 //------------------------------------------------------------------------------
937 // Linear Discriminant Analysis implementation
938 //------------------------------------------------------------------------------
939 void LDA::save(const String& filename) const {
940 FileStorage fs(filename, FileStorage::WRITE);
941 if (!fs.isOpened()) {
942 CV_Error(Error::StsError, "File can't be opened for writing!");
948 // Deserializes this object from a given filename.
949 void LDA::load(const String& filename) {
950 FileStorage fs(filename, FileStorage::READ);
952 CV_Error(Error::StsError, "File can't be opened for writing!");
957 // Serializes this object to a given FileStorage.
958 void LDA::save(FileStorage& fs) const {
960 fs << "num_components" << _num_components;
961 fs << "eigenvalues" << _eigenvalues;
962 fs << "eigenvectors" << _eigenvectors;
965 // Deserializes this object from a given FileStorage.
966 void LDA::load(const FileStorage& fs) {
968 fs["num_components"] >> _num_components;
969 fs["eigenvalues"] >> _eigenvalues;
970 fs["eigenvectors"] >> _eigenvectors;
973 void LDA::lda(InputArrayOfArrays _src, InputArray _lbls) {
975 Mat src = _src.getMat();
976 std::vector<int> labels;
977 // safely copy the labels
979 Mat tmp = _lbls.getMat();
980 for(unsigned int i = 0; i < tmp.total(); i++) {
981 labels.push_back(tmp.at<int>(i));
984 // turn into row sampled matrix
986 // ensure working matrix is double precision
987 src.convertTo(data, CV_64FC1);
988 // maps the labels, so they're ascending: [0,1,...,C]
989 std::vector<int> mapped_labels(labels.size());
990 std::vector<int> num2label = remove_dups(labels);
991 std::map<int, int> label2num;
992 for (int i = 0; i < (int)num2label.size(); i++)
993 label2num[num2label[i]] = i;
994 for (size_t i = 0; i < labels.size(); i++)
995 mapped_labels[i] = label2num[labels[i]];
996 // get sample size, dimension
999 // number of unique labels
1000 int C = (int)num2label.size();
1001 // we can't do a LDA on one class, what do you
1002 // want to separate from each other then?
1004 String error_message = "At least two classes are needed to perform a LDA. Reason: Only one class was given!";
1005 CV_Error(Error::StsBadArg, error_message);
1007 // throw error if less labels, than samples
1008 if (labels.size() != static_cast<size_t>(N)) {
1009 String error_message = format("The number of samples must equal the number of labels. Given %d labels, %d samples. ", labels.size(), N);
1010 CV_Error(Error::StsBadArg, error_message);
1012 // warn if within-classes scatter matrix becomes singular
1014 std::cout << "Warning: Less observations than feature dimension given!"
1015 << "Computation will probably fail."
1018 // clip number of components to be a valid number
1019 if ((_num_components <= 0) || (_num_components > (C - 1))) {
1020 _num_components = (C - 1);
1022 // holds the mean over all classes
1023 Mat meanTotal = Mat::zeros(1, D, data.type());
1024 // holds the mean for each class
1025 std::vector<Mat> meanClass(C);
1026 std::vector<int> numClass(C);
1028 for (int i = 0; i < C; i++) {
1030 meanClass[i] = Mat::zeros(1, D, data.type()); //! Dx1 image vector
1033 for (int i = 0; i < N; i++) {
1034 Mat instance = data.row(i);
1035 int classIdx = mapped_labels[i];
1036 add(meanTotal, instance, meanTotal);
1037 add(meanClass[classIdx], instance, meanClass[classIdx]);
1038 numClass[classIdx]++;
1040 // calculate total mean
1041 meanTotal.convertTo(meanTotal, meanTotal.type(), 1.0 / static_cast<double> (N));
1042 // calculate class means
1043 for (int i = 0; i < C; i++) {
1044 meanClass[i].convertTo(meanClass[i], meanClass[i].type(), 1.0 / static_cast<double> (numClass[i]));
1046 // subtract class means
1047 for (int i = 0; i < N; i++) {
1048 int classIdx = mapped_labels[i];
1049 Mat instance = data.row(i);
1050 subtract(instance, meanClass[classIdx], instance);
1052 // calculate within-classes scatter
1053 Mat Sw = Mat::zeros(D, D, data.type());
1054 mulTransposed(data, Sw, true);
1055 // calculate between-classes scatter
1056 Mat Sb = Mat::zeros(D, D, data.type());
1057 for (int i = 0; i < C; i++) {
1059 subtract(meanClass[i], meanTotal, tmp);
1060 mulTransposed(tmp, tmp, true);
1067 gemm(Swi, Sb, 1.0, Mat(), 0.0, M);
1068 EigenvalueDecomposition es(M);
1069 _eigenvalues = es.eigenvalues();
1070 _eigenvectors = es.eigenvectors();
1071 // reshape eigenvalues, so they are stored by column
1072 _eigenvalues = _eigenvalues.reshape(1, 1);
1073 // get sorted indices descending by their eigenvalue
1074 std::vector<int> sorted_indices = argsort(_eigenvalues, false);
1075 // now sort eigenvalues and eigenvectors accordingly
1076 _eigenvalues = sortMatrixColumnsByIndices(_eigenvalues, sorted_indices);
1077 _eigenvectors = sortMatrixColumnsByIndices(_eigenvectors, sorted_indices);
1078 // and now take only the num_components and we're out!
1079 _eigenvalues = Mat(_eigenvalues, Range::all(), Range(0, _num_components));
1080 _eigenvectors = Mat(_eigenvectors, Range::all(), Range(0, _num_components));
1083 void LDA::compute(InputArrayOfArrays _src, InputArray _lbls) {
1084 switch(_src.kind()) {
1085 case _InputArray::STD_VECTOR_MAT:
1086 lda(asRowMatrix(_src, CV_64FC1), _lbls);
1088 case _InputArray::MAT:
1089 lda(_src.getMat(), _lbls);
1092 String error_message= format("InputArray Datatype %d is not supported.", _src.kind());
1093 CV_Error(Error::StsBadArg, error_message);
1098 // Projects samples into the LDA subspace.
1099 Mat LDA::project(InputArray src) {
1100 return subspaceProject(_eigenvectors, Mat(), _dataAsRow ? src : src.getMat().t());
1103 // Reconstructs projections from the LDA subspace.
1104 Mat LDA::reconstruct(InputArray src) {
1105 return subspaceReconstruct(_eigenvectors, Mat(), _dataAsRow ? src : src.getMat().t());