opencv实现PCA降维

《learning opencv 》 ex7-3 解决方案

PCA(主成分分析)算法是数据科学领域最经典的数据降维算法之一,在之前的文章中,已经介绍过了利用Python中numpy库实现的降维方法,本篇文章,会用opencv库提供的方法,实现数据降维。

利用随机数生成器,生成一个100*3 矩阵,
a. 第一维和第二维的数据服从均值为64,方差为192的高斯分布;
b. 第三维数据服从均值为128,方差为2的高斯分布;
c.利用PCA对象计算降维后的数据,其最大主成分设置为2

其实现代码如下所示:

#include
#include

using namespace cv;

/*
1. Using cv::RNG random number generator,create an array of 100 three-byte objects such that:
    a. The first and second dimensions hava a Gaussian distribution ,centered at 64,and 192,respectively,each
        with variance of 10;
    b. The third dimension has a Guassian distribution,centered at 128,and with variance of 2;
    c. Using the cv::PCA object,compute a projection for which maxComponets=2
    d. Compute the mean in both dimensions of the projections;explain the result;
*/
int main()
{
    Mat m = Mat(100, 3, CV_32F, Scalar(0));
    RNG rng = theRNG();
    rng.fill(m.col(0), RNG::NORMAL, 64, 10);
    rng.fill(m.col(1), RNG::NORMAL, 192, 10);
    rng.fill(m.col(2), RNG::NORMAL, 128, 2);
    std::cout << m.size() << std::endl;
    Mat mean;
    reduce(m, mean, 0, ReduceTypes::REDUCE_AVG, -1);
    PCA pca_mean = PCA::PCA(m, mean,cv::PCA::Flags::DATA_AS_ROW, 2);
    Mat dst_mean = pca_mean.project(m);
    //std::cout << dst_mean << std::endl;
    //std::cout << dst_mean.size() <

你可能感兴趣的:(opencv实现PCA降维)