Struct opencv::core::PCA

source ·
pub struct PCA { /* private fields */ }
Expand description

Principal Component Analysis

The class is used to calculate a special basis for a set of vectors. The basis will consist of eigenvectors of the covariance matrix calculated from the input set of vectors. The class %PCA can also transform vectors to/from the new coordinate space defined by the basis. Usually, in this new coordinate system, each vector from the original set (and any linear combination of such vectors) can be quite accurately approximated by taking its first few components, corresponding to the eigenvectors of the largest eigenvalues of the covariance matrix. Geometrically it means that you calculate a projection of the vector to a subspace formed by a few eigenvectors corresponding to the dominant eigenvalues of the covariance matrix. And usually such a projection is very close to the original vector. So, you can represent the original vector from a high-dimensional space with a much shorter vector consisting of the projected vector’s coordinates in the subspace. Such a transformation is also known as Karhunen-Loeve Transform, or KLT. See http://en.wikipedia.org/wiki/Principal_component_analysis

The sample below is the function that takes two matrices. The first function stores a set of vectors (a row per vector) that is used to calculate PCA. The second function stores another “test” set of vectors (a row per vector). First, these vectors are compressed with PCA, then reconstructed back, and then the reconstruction error norm is computed and printed for each vector. :

using namespace cv;
 
PCA compressPCA(const Mat& pcaset, int maxComponents,
               const Mat& testset, Mat& compressed)
{
   PCA pca(pcaset, // pass the data
           Mat(), // we do not have a pre-computed mean vector,
                   // so let the PCA engine to compute it
           PCA::DATA_AS_ROW, // indicate that the vectors
                                // are stored as matrix rows
                                // (use PCA::DATA_AS_COL if the vectors are
                                // the matrix columns)
           maxComponents // specify, how many principal components to retain
           );
   // if there is no test data, just return the computed basis, ready-to-use
   if( !testset.data )
       return pca;
   CV_Assert( testset.cols == pcaset.cols );
 
   compressed.create(testset.rows, maxComponents, testset.type());
 
   Mat reconstructed;
   for( int i = 0; i < testset.rows; i++ )
   {
       Mat vec = testset.row(i), coeffs = compressed.row(i), reconstructed;
       // compress the vector, the result will be stored
       // in the i-th row of the output matrix
       pca.project(vec, coeffs);
       // and then reconstruct it
       pca.backProject(coeffs, reconstructed);
       // and measure the error
       printf("%d. diff = %g\n", i, norm(vec, reconstructed, NORM_L2));
   }
   return pca;
}

§See also

calcCovarMatrix, mulTransposed, SVD, dft, dct

Implementations§

source§

impl PCA

source

pub fn default() -> Result<PCA>

default constructor

The default constructor initializes an empty %PCA structure. The other constructors initialize the structure and call PCA::operator()().

source

pub fn new( data: &impl ToInputArray, mean: &impl ToInputArray, flags: i32, max_components: i32, ) -> Result<PCA>

default constructor

The default constructor initializes an empty %PCA structure. The other constructors initialize the structure and call PCA::operator()().

§Overloaded parameters
§Parameters
  • data: input samples stored as matrix rows or matrix columns.
  • mean: optional mean value; if the matrix is empty (@c noArray()), the mean is computed from the data.
  • flags: operation flags; currently the parameter is only used to specify the data layout (PCA::Flags)
  • maxComponents: maximum number of components that %PCA should retain; by default, all the components are retained.
§C++ default parameters
  • max_components: 0
source

pub fn new_def( data: &impl ToInputArray, mean: &impl ToInputArray, flags: i32, ) -> Result<PCA>

@overload

§Parameters
  • data: input samples stored as matrix rows or matrix columns.
  • mean: optional mean value; if the matrix is empty (@c noArray()), the mean is computed from the data.
  • flags: operation flags; currently the parameter is only used to specify the data layout (PCA::Flags)
  • maxComponents: maximum number of components that %PCA should retain; by default, all the components are retained.
§Note

This alternative version of [new] function uses the following default values for its arguments:

  • max_components: 0
source

pub fn new_with_variance( data: &impl ToInputArray, mean: &impl ToInputArray, flags: i32, retained_variance: f64, ) -> Result<PCA>

default constructor

The default constructor initializes an empty %PCA structure. The other constructors initialize the structure and call PCA::operator()().

§Overloaded parameters
§Parameters
  • data: input samples stored as matrix rows or matrix columns.
  • mean: optional mean value; if the matrix is empty (noArray()), the mean is computed from the data.
  • flags: operation flags; currently the parameter is only used to specify the data layout (PCA::Flags)
  • retainedVariance: Percentage of variance that PCA should retain. Using this parameter will let the PCA decided how many components to retain but it will always keep at least 2.

Trait Implementations§

source§

impl Boxed for PCA

source§

unsafe fn from_raw(ptr: <PCA as OpenCVFromExtern>::ExternReceive) -> Self

Wrap the specified raw pointer Read more
source§

fn into_raw(self) -> <PCA as OpenCVTypeExternContainer>::ExternSendMut

Return the underlying raw pointer while consuming this wrapper. Read more
source§

fn as_raw(&self) -> <PCA as OpenCVTypeExternContainer>::ExternSend

Return the underlying raw pointer. Read more
source§

fn as_raw_mut(&mut self) -> <PCA as OpenCVTypeExternContainer>::ExternSendMut

Return the underlying mutable raw pointer Read more
source§

impl Debug for PCA

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Drop for PCA

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl PCATrait for PCA

source§

fn as_raw_mut_PCA(&mut self) -> *mut c_void

source§

fn set_eigenvectors(&mut self, val: Mat)

eigenvectors of the covariation matrix
source§

fn set_eigenvalues(&mut self, val: Mat)

eigenvalues of the covariation matrix
source§

fn set_mean(&mut self, val: Mat)

mean value subtracted before the projection and added after the back projection
source§

fn apply( &mut self, data: &impl ToInputArray, mean: &impl ToInputArray, flags: i32, max_components: i32, ) -> Result<PCA>

performs %PCA Read more
source§

fn apply_def( &mut self, data: &impl ToInputArray, mean: &impl ToInputArray, flags: i32, ) -> Result<PCA>

performs %PCA Read more
source§

fn apply_1( &mut self, data: &impl ToInputArray, mean: &impl ToInputArray, flags: i32, retained_variance: f64, ) -> Result<PCA>

performs %PCA Read more
source§

fn read(&mut self, fn_: &impl FileNodeTraitConst) -> Result<()>

load PCA objects Read more
source§

impl PCATraitConst for PCA

source§

fn as_raw_PCA(&self) -> *const c_void

source§

fn eigenvectors(&self) -> Mat

eigenvectors of the covariation matrix
source§

fn eigenvalues(&self) -> Mat

eigenvalues of the covariation matrix
source§

fn mean(&self) -> Mat

mean value subtracted before the projection and added after the back projection
source§

fn project(&self, vec: &impl ToInputArray) -> Result<Mat>

Projects vector(s) to the principal component subspace. Read more
source§

fn project_to( &self, vec: &impl ToInputArray, result: &mut impl ToOutputArray, ) -> Result<()>

Projects vector(s) to the principal component subspace. Read more
source§

fn back_project(&self, vec: &impl ToInputArray) -> Result<Mat>

Reconstructs vectors from their PC projections. Read more
source§

fn back_project_to( &self, vec: &impl ToInputArray, result: &mut impl ToOutputArray, ) -> Result<()>

Reconstructs vectors from their PC projections. Read more
source§

fn write(&self, fs: &mut impl FileStorageTrait) -> Result<()>

write PCA objects Read more
source§

impl Send for PCA

Auto Trait Implementations§

§

impl Freeze for PCA

§

impl RefUnwindSafe for PCA

§

impl !Sync for PCA

§

impl Unpin for PCA

§

impl UnwindSafe for PCA

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<Mat> ModifyInplace for Mat
where Mat: Boxed,

source§

unsafe fn modify_inplace<Res>( &mut self, f: impl FnOnce(&Mat, &mut Mat) -> Res, ) -> Res

Helper function to call OpenCV functions that allow in-place modification of a Mat or another similar object. By passing a mutable reference to the Mat to this function your closure will get called with the read reference and a write references to the same Mat. This is unsafe in a general case as it leads to having non-exclusive mutable access to the internal data, but it can be useful for some performance sensitive operations. One example of an OpenCV function that allows such in-place modification is imgproc::threshold. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.