Sunday 22 April 2012

[FIND] function in MATLAB

Matlab is really a good tool to implement some brainstorm idea in quick way, however, for loop is not efficient especially for large database search problem. FIND built-in function can solve the problem very well. Now I understand why the runtime of compilation-based code is much more efficient than interpretation-based program.

For example, the first program is several orders of magnitude faster than the second one.

% The codes with find

for i = 1:NumQuadrats
    tic
    ind = find(x >= xmin + (i - 1)*step & x < xmin + i*step);
    quadrat{i} = [x(ind) y(ind) z(ind)];
    x(ind) = [];
    y(ind) = [];
    z(ind) = [];
    fprintf('Quadrat %d has been done !\n', i);
    toc
end

% The codes without find

for i = 1:NumQuadrats
    index = [];
    tic
    for j = 1:size(x,1)
        if x(j) >= xmin + (i - 1)*step && x(j) < xmin + i*step
            quadrat{i} = [quadrat{i};[x(j) y(j) z(j)]];
            index = [index;j];
        end
    end
    x(index) = [];
    y(index) = [];
    z(index) = [];
    fprintf('Quadrat %d has been done !\n', i);
    toc
end


Thursday 12 April 2012

OpenCV waitKey() function

Basically waitKey is the function which suspends or pauses the process for a given time, say waitKey(10) will wait 10 millisecond until running the following codes, while waitKey(0) will run the following codes unless any key is pressed.

The other important role of this function is to fetch and handle events in HighGUI calling. For example, in a loop, if you create a window (using namedWindow) and the display on the screen using imshow(). In this scenario, nothing is shown on the screen until waitKey is called, since HighGUI does not give any time for imshow to process the drawing events.


/* Assuming this is a while loop -> e.g. video stream where img is obtained from say web camera.*/    
cvShowImage("Window",img);
/* A small interval of 10 milliseconds. This may be necessary to display the image correctly */
cvWaitKey(10);  
/* to wait until user feeds keyboard input replace with cvWaitKey(0); */