# how PCA can be applied to an image to reduce its dimensionality with example?

401 views (last 30 days)

Show older comments

This question was flagged by Walter Roberson

Dimensionality reduction

##### 3 Comments

Image Analyst
on 14 Sep 2021

### Accepted Answer

Image Analyst
on 24 Dec 2014

Edited: Image Analyst
on 14 Apr 2020

Here's code I got from Spandan, one of the developers of the Image Processing Toolbox at the Mathworks:

Here some quick code for getting principal components of a color image. This code uses the pca() function from the Statistics Toolbox which makes the code simpler.

I = double(imread('peppers.png'));

X = reshape(I,size(I,1)*size(I,2),3);

coeff = pca(X);

Itransformed = X*coeff;

Ipc1 = reshape(Itransformed(:,1),size(I,1),size(I,2));

Ipc2 = reshape(Itransformed(:,2),size(I,1),size(I,2));

Ipc3 = reshape(Itransformed(:,3),size(I,1),size(I,2));

figure, imshow(Ipc1,[]);

figure, imshow(Ipc2,[]);

figure, imshow(Ipc3,[]);

In case you don’t want to use pca(), the same computation can be done without the use of pca() with a few more steps using base MATLAB functions.

Hope this helps.

-Spandan

Also attached are some full demos.

### More Answers (7)

Devan Marçal
on 13 Aug 2015

Hi,

in your example you used PCA in just one image. I have an image bank a total of ~ 800 images. If I make a loop (if, while, etc ..) using the PCA function for each image individually, will be using this command wrong or inefficiently?

Thanks a lot.

Devan

##### 8 Comments

Image Analyst
on 25 Jul 2019

Etworld, I just ran the colored chips image and it ran fine. Did you change my code at all?

Darshan: where did your colors come from? I don't understand what your "approximations" are supposed to be. But anyway, you can stitch images side by side if they are all RGB images to begin with:

wideImage = [rgbImage1, rgbImage2, rgbImage3];

Shaveta Arora
on 30 Jan 2016

Can I have the pca code used in this color image example

##### 6 Comments

Image Analyst
on 31 Jan 2016

Anitha Anbazhagan
on 17 Sep 2016

##### 1 Comment

Image Analyst
on 17 Sep 2016

Mina Kh
on 11 Dec 2016

##### 0 Comments

Arathy Das
on 20 Dec 2016

How can i extract three texture features among the 22 using PCA?

##### 1 Comment

Image Analyst
on 20 Dec 2016

I think you should start your own discussion with your own data or images. If you have 22 PCA columns, then just extract the 3 you want as usual.

pca3 = pca22(:, 1:3); % or whatever.

joynjo
on 24 Mar 2018

How to visualize the result of PCA image in pseudocolor?

##### 1 Comment

Image Analyst
on 24 Mar 2018

imshow(PC1); % Display the first principal component image.

colormap(jet(256));

F M Anim Hossain
on 6 Apr 2018

##### 0 Comments

### See Also

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!