Example usage for org.apache.commons.math.linear SingularValueDecompositionImpl getV

List of usage examples for org.apache.commons.math.linear SingularValueDecompositionImpl getV

Introduction

In this page you can find the example usage for org.apache.commons.math.linear SingularValueDecompositionImpl getV.

Prototype

public RealMatrix getV() throws InvalidMatrixException 

Source Link

Usage

From source file:trainableSegmentation.utils.PrincipalComponentAnalysis.java

public static ImagePlus getPrincipalComponents(final ImagePlus inputImage, final int patchSize,
        final int step) {
    final int maxX = (inputImage.getWidth() - patchSize);
    final int maxY = (inputImage.getHeight() - patchSize);

    final int matrixHeight = patchSize * patchSize;
    final int matrixWidth = (maxX / step + 1) * (maxY / step + 1) * inputImage.getImageStackSize();

    final double[][] matrix = new double[matrixWidth][matrixHeight];

    int n = 0;//from w w w.j  a va 2 s  .c  o m

    for (int i = 1; i <= inputImage.getImageStack().getSize(); i++) {
        final ImageProcessor ip = inputImage.getImageStack().getProcessor(i).convertToFloat();

        for (int j = 0; j < maxX; j += step)
            for (int k = 0; k < maxY; k += step) {
                final Roi roi = new Roi(j, k, patchSize, patchSize);
                ip.setRoi(roi);
                final ImageProcessor patch = ip.crop();
                float[] pixels = (float[]) patch.getPixels();

                for (int l = 0; l < matrixHeight; l++)
                    matrix[n][l] = pixels[l];

                n++;
            }

    }

    final Array2DRowRealMatrix m = new Array2DRowRealMatrix(matrix);

    // Calculate SVD and get V
    final long start = System.currentTimeMillis();

    final SingularValueDecompositionImpl svd = new SingularValueDecompositionImpl(m);

    final RealMatrix v = svd.getV();

    final long end = System.currentTimeMillis();
    IJ.log("SVD took: " + (end - start) + "ms");

    final ImageStack result = new ImageStack(patchSize, patchSize);

    for (int i = 0; i < v.getRowDimension(); i++) {
        final double[] column = new double[v.getColumnDimension()];
        for (int j = 0; j < v.getColumnDimension(); j++)
            column[j] = v.getEntry(j, i);
        result.addSlice("PCA " + i, new FloatProcessor(patchSize, patchSize, column));
    }

    return new ImagePlus("PCA", result);

}