Archive

Posts Tagged ‘matlab’

Working with 3D matrix in Matlab

November 16, 2009 mohsenam Leave a comment

To visualize the 3D matrix just consider that them as stack of images or layers.

{There is one more very important way,  that is third dimension representing the feature vector’s length}

So a(:, :, i) = all elements in the layer i, so changing i will give you next image.

where a(r,c, i) will move in the image.

a = [];
a(:,1,:) = [111 112 113 114 ; 121 122 123 124 ; 131 132 133 134];
a(:,2,:) = [211 212 213 214 ; 221 222 223 224 ; 231 232 233 234];
a(:,3,:) = [311 312 113 114 ; 321 322 323 324 ; 331 332 333 334];
a(:,4,:) = [411 412 113 114 ; 421 422 423 424 ; 431 432 433 434];
a(:,5,:)= [511 512 513 514 ; 521 522 523 524 ; 531 532 533 534];

Will make the 3D matrix ‘a’

size(a)

ans =

     3     5     4

That is there are 4 images and each image is of 3 rows and 5 cols.

But let’s Say you want to represent 3rd dimension as the feature vector  so each a(r,c, : ) represents a feature vector.

Now let’s say you want to make a 3D matrix from one feature vector.


vt = squeeze([a( 2,1, : ) ] );
vt = vt(:)';
%//make it into 2 by 3 by length(feature) matrix
%//repmat will repeat this matrix and make a 6 row matrix
%//the reshape picks the elements from the 1st col, 1st row and start moving downward in the row and so on
%//therefore each time it will meet same element as it moves down the row and fills our first image
tempT = (reshape(repmat(vt, 2*3,1), 2, 3, length(vt)));
size(tempT)
ans =
     2     3     4

Matlab Memory management

November 12, 2009 mohsenam Leave a comment

Oh it turns out that the matlab does not copy the data while passing it to the function if the function is not changing the values.
Which is big saving.
http://blogs.mathworks.com/loren/2006/05/10/memory-management-for-functions-and-variables/#1

Running Variance

November 9, 2009 mohsenam Leave a comment

Just in mid of the code wanted to find the Running Variance, just as habit typed and found not so good links.

1/N*[sum(i=1:N-1, Xi*Xi') + X*X'] – (1/N^2)*[ sum(i=1:(N-1), Xi) + X][ sum(i=1:(N-1), Xi) + X]‘

Matlab code for calculating the running Variance is as follow

%updating Mean

newMean = (newMean*(N-1) + X)/N;

sumOfSq = sumOfSq*(N-1)  + X*X';

covMat =  (1/N)*sumOfSQ - newMean*newMean'

Externally there are few links that are worth reading

Using Many Colors in the Matlab

October 29, 2009 mohsenam Leave a comment

While using the ‘plot’ function you end up using only small number of colors. I searched online to see if there are any solutions

One is given by http://blogs.mathworks.com/pick/2008/08/15/colors-for-your-multi-line-plots/

It discusses “varycolor” file. Which is very nice for generating many colors on the run.

However I found that for plotting of the poitns and data following is much distinguishable.

It is 72 element array.

clr = [ '.r';'.b'; '.g'; '.c';'.m'; '.y';...
        '*r';'*b'; '*g'; '*c';'*m'; '*y';...
        'xr';'xb'; 'xg'; 'xc';'xm'; 'xy';...
        '+r';'+b'; '+g'; '+c';'+m'; '+y';...
        'or';'ob'; 'og'; 'oc';'om'; 'oy';...
        'dr';'db'; 'dg'; 'dc';'dm'; 'dy';...
        'sr';'sb'; 'sg'; 'sc';'sm'; 'sy';...
        'pr';'pb'; 'pg'; 'pc';'pm'; 'py';...
        'hr';'hb'; 'hg'; 'hc';'hm'; 'hy';...
        'vr';'vb'; 'vg'; 'vc';'vm'; 'vy';...
        '>r';'>b'; '>g'; '>c';'>m'; '>y';...
        '.k';'xk'; '*k'; '+k';'ok'; 'dk';...
        ];

Matlab Efficient coding

October 14, 2009 mohsenam Leave a comment

The interpreter nature of Matlab keeps me always looking for coding it fast and efficient way, squeezing as much work as we can squeeze from single statement.

Searching for something about Matlab found following blog entry

http://omar-sabih.blogspot.com/2009/05/matlab-tryin-to-code-smarter.html

It’s much cleaner and better presented version is present at http://www.sajidmc.net/bn/2009/05/efficient-matlab-coding/

Although I also have my  Matlab page http://whatevericode.wordpress.com/matlab/ but it much less rigorous

connecting OpenCv with Matlab; Basic

November 13, 2008 mohsenam 9 comments

It took much of the time, but I was able to connect OpenCv with matlab.

Much thanks to the

http://www.mathworks.com/matlabcentral/fx_files/21818/1/OpenCV_And_MEX_Files_quick_guide.pdf

I took the introductory program given in the http://www.cs.iit.edu/~agam/cs512/lect-notes/opencv-intro/opencv-intro.html

Also help from

Writing C Functions in Matlab form Jason Laska http://cnx.org/content/m12348/latest/

And modified it to run through matlab.

I named it showImageMt.cpp

So the Matlab code for compiling it was

mex showImageMt.cpp

But for that you have setup the file ‘mexopts.bat‘ as described in the above pdf . You might not able to find it by searching the matlab folder. You can find the path by running the following command in the Matlab

fullfile(prefdir,’mexopts.bat’)

The contents of the file could be see by type(fullfile(prefdir,’mexopts.bat’))

The C++ opencv code is following

////////////////////////////////////////////////////////////////////////
//
//showImageMt.cpp
//
// This is a simple, introductory OpenCV program. The program reads an
// image from a file, inverts it, and displays the result.
//
////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <cv.h>
#include <highgui.h>

#include "mex.h"

void justWork(IplImage *img){
int height,width,step,channels;
uchar *data;
int i,j,k;

// get the image data
height    = img->height;
width     = img->width;
step      = img->widthStep;
channels  = img->nChannels;
data      = (uchar *)img->imageData;
printf("Processing a %dx%d image with %d channels\n",height,width,channels);

// create a window
cvNamedWindow("mainWin", CV_WINDOW_AUTOSIZE);
cvMoveWindow("mainWin", 100, 100);

// invert the image
for(i=0;i<height;i++) for(j=0;j<width;j++) for(k=0;k<channels;k++)
data[i*step+j*channels+k]=255-data[i*step+j*channels+k];

// show the image
cvShowImage("mainWin", img );

// wait for a key
cvWaitKey(0);

};

void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){

if (nrhs != 0)
{
mexErrMsgTxt("One input required.");
}
else if (nlhs > 0)
{
mexErrMsgTxt("Too many output arguments");
}

IplImage* img = 0;

/*if(argc<2){
printf("Usage: main <image-file-name>\n\7");
exit(0);
}*/

char *name = "lena.jpg";
// load an image
img=cvLoadImage(name);
if(!img){
printf("Could not load image file: %s\n",name);
exit(0);
}
justWork(img);
// release the image
cvReleaseImage(&img );
return;
}

Read more…

Categories: OpenCv, basic, matlab Tags: , , ,

Principal Component Analysis (Matlab Code)

November 6, 2008 mohsenam 17 comments

function [evec, eval, meanA] = PCA(A, maxVec)

%Principal Component Analysis
%A has th
[ rows, cols] = size(A);
if(nargin < 2)
maxVec = rows;
end

maxVec = min(maxVec, rows);

meanA = mean(A,2);
A = A – meanA*ones(1, cols);
%[evec eval] = eig(A’*A);
[evec eval] = eig(A*A’);

[eval ind]  =  sort(-1*diag(eval));
%[eval ind]  =  sort(diag(eval), ”);
eval    = -1*eval(1:maxVec);
evec    = evec(:, ind(1:maxVec));
Read more…

Hexagonal Sampling and Interpolation

April 3, 2008 mohsenam Leave a comment

%Cartesian Sampling
x1 = -10:0.5:10;
y1 = -10:0.5:10;

[x y]= meshgrid(x1, y1);
f = cos(cos(sqrt(x.^2+y.^2)));
figure;
imagesc(f);
figure
mesh(x,y, f);

%the sampling lattice is
%[x y]‘ = |sqrt(3)/2 0| |i|
% |1/2 1| |j|
%hexagonal smapling
i = x;
j = y;
x = i*sqrt(3)/2 +0;
y = i*1/2 + j;
%x = i*sqrt(3)/2 +0;
f = cos(cos(sqrt(x.^2+y.^2)));
figure;
imagesc(f);
figure
mesh(x,y, f);

%TRYING TO RECOVER ORIGNAL SAMPLING
%i = -20:0.1/1.5:20;
minx = min(x(:));
maxx = max(x(:));
miny = min(y(:));
maxy = max(y(:));

miny = y(1,end);
maxy = y(end,1);

i = minx:0.5/4:maxx;
j = miny:0.5/4:maxy;
%j = -20:0.1:20;

[x2d y2d]= meshgrid(i, j);
figure;
plot(x2d,y2d, ‘b.’);hold on; plot(x,y, ‘r*’)

v = zeros(size(x2d));
for i=1:size(x2d,1)
i
for j=1:size(x2d,2)
b = boxSplineD2(x-x2d(i,j),y- y2d(i,j));
v(i,j)= sum(sum(b.*f));

end
end

figure;
imagesc(v);
figure
mesh(x2d,y2d, v);

Hexagonal Box-Spline; Matlab Code

April 3, 2008 mohsenam Leave a comment

Implementation of the Matlab Code Present in the “Three-Directional Box-Splines: Characterization and Efficient Evaluation” by Laurent Condat, Student Member, IEEE, and Dimitri Van De Ville, Member, IEEE
————————————————————————————————————

%2 degree

————————————————————————————————————

function b = boxSplineD2(x,y)

u = abs(x)-abs(y)/sqrt(3);
v = abs(x)+abs(y)/sqrt(3);
b = zeros(size(x));

ind = find(u <0);
u(ind) = -u(ind);
v(ind) = v(ind)+ u(ind);

ind = find(2*u <v);
u(ind) = v(ind)- u(ind);

g = u – v/2;

b = 5/6 + ((1+(1/3 – v/8).*v).*v/4-1).*v + …
((1-v./4).*v+g.*g./6-1).*g.*g;

ind = find(v < 1);
vi = v(ind);
gi = g(ind);
b(ind) = 0.5 + ((5/3-vi/8).*vi-3).*vi.*vi/4+((1-vi/4).*vi+gi.*gi/6.0-1).*gi.*gi;
clear vi gi;

————————————————————————————————————

%n-degree

————————————————————————————————————

function val = boxSplineDn(x,y, n)
x = -abs(x);
y = abs(y);

u = x-y/sqrt(3);
v = x+y/sqrt(3);
id = find(v>0);     v(id) = -v(id); u(id)=u(id)+v(id);

id = find(v > u/2); v(id) = u(id)-v(id);
val = zeros(size(x));

for K=-n:(ceil(max(max(u)))-1)
for L = -n:(ceil(max(max(v)))-1)
for i=0:min(n+K,n+L)
coeff = (-1)^(K+L+i)*nchoosek(n,i-K)*nchoosek(n,i-L)*nchoosek(n,i);
for d=0:n-1
aux = abs(v-L-u+K);
aux2= (u-K+v-L-aux)/2;
aux2(find(aux2<0))=0;
val =val + coeff*nchoosek(n-1+d,d)/…
factorial(2*n-1+d)/factorial(n-1-d)*…
aux.^(n-1-d).*aux2.^(2*n-1+d);
end
end
end
end
ind = find(u > 1);

b(ind) = ((v(ind)-2).^3).*(g(ind)-1)/6;
ind = find(v>2);
b(ind) = 0;      %outside support

%b = b/(sum(sum(b)));

Genrating Gaussian Mask

March 24, 2008 mohsenam Leave a comment

Matlab file for the Gaussian Mask

For some of the masks already generated you can go to http://whatevericode.wordpress.com/2008/04/08/gaussian-masks/

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function mask =gaussMask(stdIn)
varIn = stdIn*stdIn;
T = 0.1;
halfSize = round(sqrt(-2*log(T)*varIn))
[x y] = meshgrid(-halfSize:halfSize, -halfSize:halfSize);

mask = (1/(2*pi*varIn))*exp(-0.5*(x.^2 + y.^2)/varIn);
weight = sum(sum(mask));

mask = mask./weight;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%