I have an image. I need to identify the axis along which the variance of the image is the smallest. A bit of reading and searching led me to the conclusion that Principal Component Analysis(PCA) is the best alternative. Can anyone help me with orienting the image with respect to its principal axis? Since i am recently introduced to matlab i find it a bit difficult. An example of the image is below. I am trying to rotate the image so that i can generate the histogram.
I haven't used PCA as yet my current code is as shown below
enter code here
I2='image'
I11= bwlabel(I2);
OBB = imOrientedBox(I11);
obbsize=[];
for i=1:size(OBB,1)
obbsize=[obbsize,OBB(i,3)*OBB(i,4)];
end
[a,i]=max(obbsize);
I11=(imrotate(I2,OBB(i,5)));
imshow(I11,[])
[pks,locs] =findpeaks(sum(I11,2));
[M1,Indx1] = max(pks);
imshow(I11(1:locs(Indx1),1:size(I11,2)),[])
Construct your PCA transformation matrix using. C is your transformation or your rotation matrix that will transform it to your highest variance directions.
[C,~,~,~,explained] = pca( data );
Remove PC if you wish to truncate components (say 1-5 components). If you don't need to truncate/reduce dimensions, ignore this step.
C = C(:,1:5);
Create the transformed data using the transformation C
. The data will now be in the new transformed space with the first dimension being the largest variance, second dim being the second largest variance, etc. Since you are looking for the least variance, that is the last dimension
tfData = data * C;
Process your data accordingly in this new transformed space. To obtain your inverse transformation and put it back to the original space, use the following.
origAxisData = tfData * C';
The transpose operation C'
is the same as the inverse operation inv(C)
for the inverse transformation as it is orthogonal as described here. However the transpose is much faster to calculate than the inverse, especially for high dimensions.
You can plot your principal component/axes/kernel by plotting the columns of C as follows.
for i = 1:length(end)
figure; plot( C(:,1) );
end