Quantcast
Channel: OpenCV Q&A Forum - Latest question feed
Viewing all articles
Browse latest Browse all 19555

Feature Extraction using PCA in opencv 3.0 c++

$
0
0
I'm new to opencv 3.0 and pca and I need help . [ Using PCA module to extract the features from contour of one image.(feature extraction)] I Need to subtract the mean.-The average image a has to be calculated and then subtracted from each original image in T. I need to calculate the eigenvectors and eigenvalues of the covariance matrix S. Firstly I need to do the covariance matrix of data,then calculate the eigenvectors and eigenvalues from the covariance matrix and finally store the matrix! What is missing in the code ? #include #include #include "opencv2/imgcodecs.hpp" #include #include #include using namespace cv; using namespace cv::ml; using namespace std; //save mean,eigenvectors and eigenvalues void save(const string &file_name, cv::PCA pca_) { FileStorage fs(file_name, FileStorage::WRITE); fs << "mean" << pca_.mean; fs << "e_vectors" << pca_.eigenvectors; fs << "e_values" << pca_.eigenvalues; fs.release(); } void load(const string &file_name, cv::PCA pca_) { FileStorage fs(file_name, FileStorage::READ); fs["mean"] >> pca_.mean; fs["e_vectors"] >> pca_.eigenvectors; fs["e_values"] >> pca_.eigenvalues; fs.release(); } Mat normalize(const Mat& src) { Mat srcnorm; normalize(src, srcnorm, 0, 255, NORM_MINMAX, CV_8UC1); return srcnorm; } PCA pca(const Mat& pcaset, int maxComponents) { int n = pcaset.rows, p = pcaset.cols; cout << "\tcalculating 'true' means, variance and standard deviation..." << endl; Mat means(1, p, CV_32FC1); Mat variance(1, p, CV_32FC1); for (size_t i = 0; i < p; i++) { float avg = mean(pcaset.col(i)).val[0]; means.at(0, i) = avg; Mat p2 = Mat(1, n, CV_32F); for (size_t j = 0; j < n; j++) p2.at(0, j) = pow(pcaset.at(j, i), 2); variance.at(0, i) = (1 / (float)n) * sum(p2).val[0] - pow(avg, 2); } //covariance matrix, AA', not the A'A like usual Mat M; Mat centred(n, p, CV_32FC1); for (size_t i = 0; i < n; i++) centred.row(i) = (pcaset.row(i) - means) / variance; mulTransposed(centred, M, 0); //compute eigenvalues and eigenvectors PCA pca; pca = PCA(M, cv::Mat(), CV_PCA_DATA_AS_ROW, maxComponents); pca.mean = means; pca.eigenvectors = pca.eigenvectors * centred; pca.eigenvectors = pca.eigenvectors.rowRange(Range(0, maxComponents)); return pca; } //load image Mat src = imread("pic.jpg"); int main() { Size size(64, 128); resize(src, src, size); //set PCA parameters // Number of components to keep for the PCA: int num_components = 10; // Perform a PCA: PCA pca(src, cv::Mat(), CV_PCA_DATA_AS_ROW, num_components); cout << pca.eigenvalues.rows << endl; // And copy the PCA results: Mat mean = pca.mean.clone(); Mat eigenvalues = pca.eigenvalues.clone(); Mat eigenvectors = pca.eigenvectors.clone(); return 0; }

Viewing all articles
Browse latest Browse all 19555

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>