How to apply PCA on a cell containing matrices of images?
4 views (last 30 days)
Show older comments
Hi! I am working on a project wherein I have a dataset containing multiple images and I want to apply PCA on it to find principle componenets. The inbuilt command 'princomp' cannot be used on it so I started applying each step separately. Now I have to find eigen values however 'eig' does not work on cells. How to proceed?
eye_dbcrop_m{1,300} - cell containing images after subtraction of mean from them. How to find eigen vectors and eigen values of this cell? Or how to convert this cell to a matrix?
0 Comments
Answers (1)
Aditya
on 4 Feb 2025
Hi Mahila,
To apply PCA to a dataset containing multiple images, you need to convert the image data into a suitable matrix format for processing. Typically, each image is flattened into a vector, and these vectors are stacked to form a matrix where each row (or column) represents an image. Once you have this matrix, you can compute the covariance matrix and find the eigenvalues and eigenvectors. Following is an example code:
% Example: Assume images are grayscale and of size m x n
numImages = size(eye_dbcrop_m, 2);
imageSize = size(eye_dbcrop_m{1}); % Assuming all images are the same size
flattenedSize = prod(imageSize);
% Initialize a matrix to hold the flattened images
X = zeros(numImages, flattenedSize);
% Flatten each image and store it as a row in the matrix X
for i = 1:numImages
img = eye_dbcrop_m{i};
X(i, :) = img(:)'; % Flatten and store as a row
end
% Subtract the mean from each pixel (column)
X_mean = mean(X, 1);
X_centered = X - X_mean;
% Compute the covariance matrix
covMatrix = cov(X_centered);
% Compute eigenvalues and eigenvectors
[eigenvectors, eigenvaluesMatrix] = eig(covMatrix);
% Extract eigenvalues from the diagonal matrix
eigenvalues = diag(eigenvaluesMatrix);
% Sort eigenvalues and corresponding eigenvectors
[eigenvaluesSorted, idx] = sort(eigenvalues, 'descend');
eigenvectorsSorted = eigenvectors(:, idx);
For further information please refer to the following documentation:
0 Comments
See Also
Categories
Find more on Dimensionality Reduction and Feature Extraction in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!