Google
 

7/18/07

Install source navigator failed.

I tried to install this program, but had very hard time. At the beginning the computer complaining that it can not find the tcl script file. This part is solved by:

configure --help
There is an option --withtclconfig, use this option as: --withtclconfig=/usr/lib/tcl8.4/
This is solved. But when I use "make" to compile the program, it says no rules to xxx libdb.a. I have libdb.a in my /usr/lib/ though.

Anyway, I don't want to spend more time on this stupid program any more.

6/8/07

compile cpp with opencv.

In order to use opencv, when you compile the program you need to use the following:
g++ `pkg-config --cflags opencv` -o test test.cpp `pkg-config --libs opencv`
Or you can execute the commands to get the parameters used.
> pkg-config --cflags opencv
-I/usr/local/include/opencv
> pkg-config --libs opencv
-L/usr/local/lib -lcxcore -lcv -lhighgui -lcvaux -lml
Now you can use something similar to the following:
> g++ -I/usr/local/include/opencv -o test opencv_test.cpp -L/usr/local/lib/ -lcxcore -lhighgui -lm

5/19/07

Adding extra fonts.

Adding Extra Fonts

The fonts that come with X are quite limited. You may want to install the msttcorefonts package to provide Microsoft TrueType core fonts for use in X.

To install them, run

apt-get install msttcorefonts

at the command line as root. If you get an error

E: Couldn't find package msttcorefonts

you may need to edit your /etc/apt/sources.list to include the contrib section in your source entry.

5/16/07

Install and use dislin under linuxe (debian).

1. Download and install the library according to the README file.
2. Copy /usr/local/dislin/dislin.h to /usr/local/include/
3. Copy /usr/local/dislin/libdislin.a to /usr/local/lib/
Now it should work using the following options when compile the program.
> g++ test.cpp -lXt -ldislin -lm
Don't forget the -lXt

Another option is:
> g++ test.cpp /usr/local/dislin/lib/dislin-9.1.a -lm -L/usr/X11R6/lib -lXt

I assumed in the above example that dislin is installed in: /usr/local/dislin/. There is no need to change /etc/profile or set the envionment varibles as the README suggested. Here is a very useful link:

http://people.scs.fsu.edu/~burkardt/cpp_src/dislin/dislin.html


Use dislin:
//
// Specify the format of the output file.
//
// metafl ( "PNG" ); //if want to save as png file
metafl("XWIN"); //this just show the graph on screen
//
// Specify the name of the output graphics file.
//
// setfil ( "dislin_ex01.png" ); //only when you want to save the figure.

disini ( );
pagera ( );
complx ( );
axspos ( 450, 1800 );
axslen ( 2200, 1200 );

name ( "X-axis", "x" );
name ( "Y-axis", "y" );

labdig ( -1, "x" );
ticks ( 10, "xy" );

titlin ( "Demonstration of CURVE", 1 );
titlin ( "SIN(X), COS(X)", 3 );

graf ( 0.0, 360.0, 0.0, 90.0, -1.0, 1.0, -1.0, 0.5 );
title ( );

color ( "red" );
curve ( xray, y1ray, N ); //This is the data transfer part.

color ( "green" );
curve ( xray, y2ray, N );

color ( "fore" );
dash ( );
xaxgit ( );

disfin ( );

5/13/07

Make movie using imagemagick.

Command-line animations using ImageMagick

Tuesday July 12, 2005 (09:01 AM GMT)
By: Shashank Sharma

Printer-friendly Email story

If the success of the "Shrek," "Toy Story," "Stuart Little," "The Incredibles," and many other Hollywood hits is any indication, animations add glitz to the mundane. While animation in the movies still requires professional animation packages like Blender, you can make simple animations using the command-line wizardry of ImageMagick.

There are three basic steps to making an animation. First you need an idea. Next, you need a set of images to run through in individual frames. You can get the images from your digital camera or your scanner or draw them using ImageMagick or the GIMP. Once you have these ready, all you need to do is to put them together into an animation.

Your first animation

A basic animation could just run through several images. You can do this easily using the animate command:

animate image1.gif image2.gif image3.gif

Basic Animation
A basic animation

IM displays the images in the order they are listed. Since animate does not save animations, its use is limited to testing. This animation will quickly blur through all the three GIF files.

If you need to pause on an image before moving to the next one, use the -delay switch. It sets the time pause between images in units of 100th of a second:

animate -delay 200 frame1.gif frame2.gif frame3.gif

This sequence of images will spend two seconds on each image. But this command runs the animation just once. It's left to the -loop switch to determine the number of times an animation is to cycle through the frames:

animate -delay 300 frame1.gif frame2.gif frame3.gif -loop 3

This loops the animation three times. -loop 0 loops the animation infinitely.

Placing images

To save an animation we use the convert command, supplying a filename with an appropriate extension. Use .gif if you want to use your animation on a Web site, or use .mpeg and .avi if you want these to play on a media player.

convert -delay 30 frame1.gif frame2.gif frame3.gif \
> -loop 0 playme.gif

This results in an animation, playme.gif, made up of three images looping infinitely.

The animations we have creating so far adjust their size depending upon the size of the constituent images. This can cause havoc if you use them within Web pages. We need to specify a canvas on which to lay out our animation and its constituent images. Let's use a big canvas and place the same image onto it at different places:

convert -delay 0 -size 100x100 xc:green \
> -delay 50 -page +32+62 ball.gif -page +2+35 ball.gif \
> -delay 10 -page +31+2 ball.gif -page +62+32 ball.gif \
> -loop 0 anim.gif

The -page switch places the images at the specified locations. We have also used -delay with every image to set its own pause time.

You can also use the -pause switch to supply the time delay between animation loops:

convert -delay 0 -size 100x100 xc:green \
> -delay 50 -page +32+62 ball.gif -page +2+35 ball.gif \
> -delay 10 -page +31+2 ball.gif -page +62+32 ball.gif \
> -loop 0 -pause 3 anim.gif

The anim.gif image is a green canvas of 100x100 pixels, within which the same image is displayed at multiple locations, each for a specified time, and the sequence repeats after three seconds.

Note that in this animation, new images appear alongside other images. If you want the previous image to disappear before the new one arrives on a clean canvas, use the -dispose switch. It controls the way an image should to be treated after being displayed:

convert -dispose none -delay 0 base.gif \
> -dispose previous -delay 100 \
> -page +32+62 ball.gif -page +2+35 ball.gif \
> -page +31+2 ball.gif -page +62+32 ball.gif \
> -loop 0 animation.gif

An animation made with the dispose previous switch
An animation made with the dispose previous switch

The most important option of dispose is previous. In an animation, the images before dispose previous become the base image, and the animation returns to this base image after each image is displayed. The dispose in the base image in the example above is thus set to zero. So, base.gif becomes the base image, and the animation returns to it after displaying each image in the sequence. So, the effective order of the animation is: base.gif->big.gif->base.gif->ball.gif->base.gif->c ircle.gif, and so on.

Using convert you can also combine two animations into one file:

convert animation.gif anim.gif combined_anim.gif

This combines the first two GIF files into the last animation in the listed sequence.

Conclusion

ImageMagick is a robust command-line utility capable of doing simple image manipulations like cropping images and changing image formats to drawing various shapes, mosaics, and 3D images to creating animations.

You can create some interesting animations using the commands in this article. You could animate trees swaying in the winds, create ripples in a pond, show cloud movement through the sky, or lip-sync yourself to "Hasta la vista, baby."

Shashank Sharma is a computer science student who loves to write about free and open source software for new users.

Slashdot Slashdot it!

5/12/07

mtl problem.

in the install file, it is said it is not necessary to install. But it turn out there is something tricky. I just copied the mtl folder to the /usr/local/include, and it doesn't work. The computer complained that std::enum etc. has multiple defination. After I recompile the mtl from source, the problem solved. I don't know exactly what it did when I compile mtl.
I did the following:
1. untar/unzip the file.
2. cd mtl
3. ./configure
4. su to root
5. make install
That is it. And the problem solved. There is something stupid MTL did. I will finally get rid of mtl from my program. It is not a very good library, at least for my code. I will use uBlast or TNT instead.

5/10/07

Function Objects in C++

Frequently we need to treat a function as a first class object in C++. One place these are frequently needed is in numerical methods code. For example a numerical integrator needs to somehow be handed a function to integrate. Some languages do this easily: for example functional languages such as Lisp and Haskell. But C++ is a little weaker in this regard.

Pointers to Functions

In the old days of C the way to do this was to hand in a pointer to a function. In fact this is exactly what is used throughout Numerical Recipes in C [2]. An example in that style is the following:


float f(float x) {
float y = 2;
float z = 3;
return x*x+y*y+z*z;
}

int main() {
. . .
. . .
integrate(&f,0,1);
. . .
}

But this has some problems. What if we have a function f() of three arguments but want to integrate it along the line y=2, z=3. We need to integrate a helper function

float f(float x,float y,float z) {
return x*x+y*y+z*z;
}

float g(float x) {
return f(x,y,z);
}

float y,z;

int main() {
. . .
. . .
y = 2;
z = 3;
integrate(&g,0,1);
. . .
}

Virtual Functions

That's a pretty ugly solution requiring a global variable. In order to lose the global variables a void * argument is added to the function to be integrated and to the integrate() function. The void * can be handed into the integrand which can dereference it to find a package containing extra arguments. A full example might look like:



struct Data {
float y,z;
};

float f(float x,void *d) {
Data *p = (Data *)d;
return x*x+p->y*p->y+p->z*p->z;
}

int main() {
. . .
. . .
Data d;
d.y = 2;
d.z = 3;
integrate(f,0,1,&d);
. . .
}

That's pretty horrible even though it's more or less the standard in the C world! In Scheme we can simply build a function on the fly like: (lambda (x) (f x y z)). Can we do something like this in C++?

C++ has a mechanism for handling pointers to functions that hides the fact that you are manipulating pointers to functions: virtual functions. Using these we can have our integrator function call a function whose identity isn't yet determined at runtime. Here's an example:



class Integrand {
public:
float evaluate(float) = 0;
float integrate(float x0,float x1) {
. . .
}
};

class F : public Integrand {
float y,z;
public:
Integrand(float y0,float z0) : y(y0), z(z0) {
}
float evaluate(float x) {
return x*x+y*y+z*z;
}
}

int main() {
. . .
. . .
F f(2,3);
integrate(f,0,1);
. . .
}

That's certainly much more elegant. But unfortunately it's authoritarian. It forces users of the integrate method to derive their functions from Integrand. What if you want to hand the same function to a numerical differentiator? Will you have to write the same function again, only derived from another base class? It would be nice if we could make completely generic function objects that can be used in multiple ways.

Generic Function Objects via Templates

The next approach is much more generic. It makes only one assumption about the function object that is passed in - that has operator() defined. (Incidentally, objects with such a method are often called functors or functoids. The latter is to be preferred as the former already has a perfectly good but quite different meaning.)


template
float integrate(const F &f,float x0,float x1) {
. . .
. . . f(x) . . .
. . .
}

class F {
float y,z;
public:
F(float y0,float z0) : y(y0), z(z0) { }
float operator()(float x) const {
return x*x+y*y+z*z;
}
};

int main() {
. . .
. . .
F f(2,3);
integrate(f,0,1);
. . .
}
This has many great advantages. The function object, f, can be pointer to a function: integrate(sin,0,1) would work for example Or it can be an object with operator() defined. One nice advantage over using virtual functions and function pointers is that it can use knowledge about the function object at runtime to optimise.

What we've actually made here is what computer scientists call a closure [3]. That's an aggregate made of a function and some of its arguments. We can't yet evaluate it because we don't yet know all of its arguments, so it's in a kind of suspended animation waiting for its final arguments.

Polymorphic Function Objects

But there's one more thing that would make the function objects even more useful. Suppose that our integral method had a whole battery of algorithms that it could throw at an integrand. Maybe one of those methods involves evaluating the function at complex arguments. As it stands this would be impossible. F only defines operator()(float) and so can only operate on floats. We'd like to write our function in a type independent way. What springs to mind is a polymorphic function object. Unfortunately there is no way to take the address of a polymorphic function. But there is a simple modification we can make to the class F above. Here it is:


class F {
float y,z;
public:
F(float y0,float z0) : y(y0), z(z0) { }
template
X operator()(X x) const {
return x*x+y*y+z*z;
}
};

With the help of a template member function F is truly polymorphic. Our integration algorithm can throw any type it likes at F, as long as the methods operator() uses understand. In fact, it's even possible for the integrate function to reconstruct a symbolic representation of the function for a large class of functions by applying operator() to symbolic types that have the arithmetic operators appropriately defined. With a little extra work we can do some real functional programming and even port Haskell code [1] directly to C++..

We have now come a long way from old-fashioned C function pointers.

References

[1] fc++: Functional Programming in C++
[2] Numerical Recipes
[3] Functions and Closures

function object or functors.

Defining a Function Object
By Danny Kalev

from the following link:
http://www.inquiry.com/techtips/cpp_pro/10min/10min0100.asp

Although pointers to functions are widely used for implementing function callbacks, C++ offers a significantly superior alternative to them, namely function objects. Function objects (also called "functors") are ordinary class objects that overload the () operator. Thus, syntactically, they behave like ordinary functions.

There are several advantages in using a function object instead of a pointer to function. First, they are more resilient to design changes because the object can be modified internally without changing its external interface. A function object can also have data members that store the result of a previous call. When using ordinary functions, you need to store the result of a previous call in a global or a local static variable. However, global and local static variables have some undesirable characteristics. Finally, compilers can inline a call made through a function object, thereby enhancing performance even further. In contrast, it is nearly impossible to inline a function call made through a pointer.

This solution will show how to define and use a function object that implements a negation operation. The first step consists of declaring an ordinary class and overloading the () operator:

class Negate
{
public:
int operator() (int n) { return -n;}
};

The overloaded () might look a bit confusing because it has two pairs of parentheses. Remember that the first pair is always empty because it serves as the operator's name; the parameter list appears in the second pair of parentheses. Unlike other overloaded operators, whose number of parameters is fixed, the overloaded () operator may take any number of parameters.

Because the built-in negation operator is unary (it takes only a single operand), our overloaded () operator also takes a single parameter. The return type is identical to the parameter's type—int, in our example. The function body is trivial; it simply returns the negated argument.

Using the Function Object
We now define a function named Callback() to test our function object. Callback() takes two arguments: an int and a reference to Negate. Callback() treats neg, the function object, as if it were a function's name:

#include
using std::cout;

void Callback(int n, Negate & neg)
{
int val = neg(n); //1 invoke overloaded ()
cout << val =" neg.operator()(n);" t=""> T operator() (T t) const {return -t;}
};

int main()
{
GenericNegate negate;
cout<<> or less<> to sort() to force a descending or ascending sorting order, respectively:

#include // for greater<> and less<>
#include //for sort()
#include
using namespace std;

int main()
{
vector vi;
//..fill vector
sort(vi.begin(), vi.end(), greater() );//descending
sort(vi.begin(), vi.end(), less() ); //ascending
}



gdb problem.

I had gdb problem. It complained "no symbol table", something like that. I don't know exactly how I fixed it. But it seems that after I installed the following packages, it disappeared.

libstdc++2.10-dbg
libstdc++2.10-dev
libstdc++5-3.3-dev
libstdc++6-dbg
libstdc++6-dev
libstdc++6-4.1-dev

then restared kdevelop, now it works! Also make sure that the -g option is in the compile options.

check the dynamic link problem.

when I used gnuplot, it gives some error. Use the following to check and find the reasons for the error.


> ldd `which gnuplot`
linux-gate.so.1 => (0xffffe000)
libreadline.so.5 => /lib/libreadline.so.5 (0xb7ee5000)
libncurses.so.5 => /lib/libncurses.so.5 (0xb7ea4000)
libz.so.1 => /usr/lib/libz.so.1 (0xb7e8f000)
libstdc++.so.5 => not found
libm.so.6 => /lib/tls/i686/cmov/libm.so.6 (0xb7e6a000)
libgcc_s.so.1 => /lib/libgcc_s.so.1 (0xb7e5f000)
libc.so.6 => /lib/tls/i686/cmov/libc.so.6 (0xb7d2e000)
libdl.so.2 => /lib/tls/i686/cmov/libdl.so.2 (0xb7d2a000)
/lib/ld-linux.so.2 (0xb7f31000)
It is clear that libstdc++.so.5 not found. So need to install it.

5/4/07

introduction to programming with openCV

Please note that this article is from the following link. Sometimes, the good articles on the web just disappear due to different reasons. I copy this one here just for my reference. Please refer to the original one.


Introduction to programming with OpenCV

Gady Agam

Department of Computer Science

January 27, 2006

Illinois Institute of Technology

Abstract:

The purpose of this document is to get you started quickly with OpenCV without having to go through lengthy reference manuals. Once you understand these basics you will be able to consult the OpenCV manuals on a need basis.


Contents

Introduction

Description of OpenCV

  • General description
    • Open source computer vision library in C/C++.
    • Optimized and intended for real-time applications.
    • OS/hardware/window-manager independent.
    • Generic image/video loading, saving, and acquisition.
    • Both low and high level API.
    • Provides interface to Intel's Integrated Performance Primitives (IPP) with processor specific optimization (Intel processors).

  • Features:
    • Image data manipulation (allocation, release, copying, setting, conversion).
    • Image and video I/O (file and camera based input, image/video file output).
    • Matrix and vector manipulation and linear algebra routines (products, solvers, eigenvalues, SVD).
    • Various dynamic data structures (lists, queues, sets, trees, graphs).
    • Basic image processing (filtering, edge detection, corner detection, sampling and interpolation, color conversion, morphological operations, histograms, image pyramids).
    • Structural analysis (connected components, contour processing, distance transform, various moments, template matching, Hough transform, polygonal approximation, line fitting, ellipse fitting, Delaunay triangulation).
    • Camera calibration (finding and tracking calibration patterns, calibration, fundamental matrix estimation, homography estimation, stereo correspondence).
    • Motion analysis (optical flow, motion segmentation, tracking).
    • Object recognition (eigen-methods, HMM).
    • Basic GUI (display image/video, keyboard and mouse handling, scroll-bars).
    • Image labeling (line, conic, polygon, text drawing)

  • OpenCV modules:
    • cv - Main OpenCV functions.
    • cvaux - Auxiliary (experimental) OpenCV functions.
    • cxcore - Data structures and linear algebra support.
    • highgui - GUI functions.

Resources

  • Reference manuals:
    • /docs/index.htm

  • Web resources:
    • Official webpage: http://www.intel.com/technology/computing/opencv/

    • Software download: http://sourceforge.net/projects/opencvlibrary/

  • Books:
    • Open Source Computer Vision Library by Gary R. Bradski, Vadim Pisarevsky, and Jean-Yves Bouguet, Springer, 1st ed. (June, 2006).

  • Sample programs for video processing (in /samples/c/):
    • color tracking: camshiftdemo
    • point tracking: lkdemo
    • motion segmentation: motempl
    • edge detection: laplace

  • Sample programs for image processing (in /samples/c/):
    • edge detection: edge
    • segmentation: pyramid_segmentation
    • morphology: morphology
    • histogram: demhist
    • distance transform: distrans
    • ellipse fitting: fitellipse

OpenCV naming conventions

  • Function naming conventions:
        cvActionTargetMod(...)

    Action = the core functionality (e.g. set, create)
    Target = the target image area (e.g. contour, polygon)
    Mod = optional modifiers (e.g. argument type)

  • Matrix data types:
        CV_(S|U|F)C

    S = Signed integer
    U = Unsigned integer
    F = Float

    E.g.: CV_8UC1 means an 8-bit unsigned single-channel matrix,
    CV_32FC2 means a 32-bit float matrix with two channels.

  • Image data types:
        IPL_DEPTH_(S|U|F)

    E.g.: IPL_DEPTH_8U means an 8-bit unsigned image.
    IPL_DEPTH_32F means a 32-bit float image.

  • Header files:
        #include 
    #include
    #include
    #include // unnecessary - included in cv.h

Compilation instructions

  • Linux:
    g++ hello-world.cpp -o hello-world \
    -I /usr/local/include/opencv -L /usr/local/lib \
    -lm -lcv -lhighgui -lcvaux

  • Windows:
    In the project preferences set the path to the OpenCV header files and
    the path to the OpenCV library files.

Example C Program

////////////////////////////////////////////////////////////////////////
//
// hello-world.cpp
//
// This is a simple, introductory OpenCV program. The program reads an
// image from a file, inverts it, and displays the result.
//
////////////////////////////////////////////////////////////////////////
#include
#include
#include
#include
#include


int main(int argc, char *argv[])
{
IplImage* img = 0;
int height,width,step,channels;
uchar *data;
int i,j,k;

if(argc<2){>\n\7");
exit(0);
}

// load an image
img=cvLoadImage(argv[1]);
if(!img){
printf("Could not load image file: %s\n",argv[1]);
exit(0);
}

// 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

GUI commands

Window management

  • Create and position a window:
      cvNamedWindow("win1", CV_WINDOW_AUTOSIZE);
    cvMoveWindow("win1", 100, 100); // offset from the UL corner of the screen

  • Load an image:
      IplImage* img=0;
    img=cvLoadImage(fileName);
    if(!img) printf("Could not load image file: %s\n",fileName);

  • Display an image:
      cvShowImage("win1",img);

    Can display a color or grayscale byte/float-image. A byte image is assumed to have values in the range $[0..255]$. A float image is assumed to have values in the range $[0..1]$. A color image is assumed to have data in BGR order.

  • Close a window:
      cvDestroyWindow("win1");

  • Resize a window:
      cvResizeWindow("win1",100,100); // new width/heigh in pixels

Input handling

  • Handle mouse events:
    • Define a mouse handler:
        void mouseHandler(int event, int x, int y, int flags, void* param)
      {
      switch(event){
      case CV_EVENT_LBUTTONDOWN:
      if(flags & CV_EVENT_FLAG_CTRLKEY)
      printf("Left button down with CTRL pressed\n");
      break;

      case CV_EVENT_LBUTTONUP:
      printf("Left button up\n");
      break;
      }
      }

      x,y: pixel coordinates with respect to the UL corner

      event: CV_EVENT_LBUTTONDOWN, CV_EVENT_RBUTTONDOWN, CV_EVENT_MBUTTONDOWN,
      CV_EVENT_LBUTTONUP, CV_EVENT_RBUTTONUP, CV_EVENT_MBUTTONUP,
      CV_EVENT_LBUTTONDBLCLK, CV_EVENT_RBUTTONDBLCLK, CV_EVENT_MBUTTONDBLCLK,
      CV_EVENT_MOUSEMOVE:

      flags: CV_EVENT_FLAG_CTRLKEY, CV_EVENT_FLAG_SHIFTKEY, CV_EVENT_FLAG_ALTKEY,
      CV_EVENT_FLAG_LBUTTON, CV_EVENT_FLAG_RBUTTON, CV_EVENT_FLAG_MBUTTON

    • Register the handler:
        mouseParam=5;
      cvSetMouseCallback("win1",mouseHandler,&mouseParam);

  • Handle keyboard events:
    • The keyboard does not have an event handler.

    • Get keyboard input without blocking:
        int key;
      key=cvWaitKey(10); // wait 10ms for input

    • Get keyboard input with blocking:
        int key;
      key=cvWaitKey(0); // wait indefinitely for input

    • The main keyboard event loop:
        while(1){
      key=cvWaitKey(10);
      if(key==27) break;

      switch(key){
      case 'h':
      ...
      break;
      case 'i':
      ...
      break;
      }
      }

  • Handle trackbar events:
    • Define a trackbar handler:
        void trackbarHandler(int pos)
      {
      printf("Trackbar position: %d\n",pos);
      }

    • Register the handler:
        int trackbarVal=25;
      int maxVal=100;
      cvCreateTrackbar("bar1", "win1", &trackbarVal ,maxVal , trackbarHandler);

    • Get the current trackbar position:
        int pos = cvGetTrackbarPos("bar1","win1");

    • Set the trackbar position:
        cvSetTrackbarPos("bar1", "win1", 25);

Basic OpenCV data structures

Image data structure

  • IPL image:
    IplImage
    |-- int nChannels; // Number of color channels (1,2,3,4)
    |-- int depth; // Pixel depth in bits:
    | // IPL_DEPTH_8U, IPL_DEPTH_8S,
    | // IPL_DEPTH_16U,IPL_DEPTH_16S,
    | // IPL_DEPTH_32S,IPL_DEPTH_32F,
    | // IPL_DEPTH_64F
    |-- int width; // image width in pixels
    |-- int height; // image height in pixels
    |-- char* imageData; // pointer to aligned image data
    | // Note that color images are stored in BGR order
    |-- int dataOrder; // 0 - interleaved color channels,
    | // 1 - separate color channels
    | // cvCreateImage can only create interleaved images
    |-- int origin; // 0 - top-left origin,
    | // 1 - bottom-left origin (Windows bitmaps style)
    |-- int widthStep; // size of aligned image row in bytes
    |-- int imageSize; // image data size in bytes = height*widthStep
    |-- struct _IplROI *roi;// image ROI. when not NULL specifies image
    | // region to be processed.
    |-- char *imageDataOrigin; // pointer to the unaligned origin of image data
    | // (needed for correct image deallocation)
    |
    |-- int align; // Alignment of image rows: 4 or 8 byte alignment
    | // OpenCV ignores this and uses widthStep instead
    |-- char colorModel[4]; // Color model - ignored by OpenCV

Matrices and vectors

  • Matrices:
    CvMat                      // 2D array
    |-- int type; // elements type (uchar,short,int,float,double) and flags
    |-- int step; // full row length in bytes
    |-- int rows, cols; // dimensions
    |-- int height, width; // alternative dimensions reference
    |-- union data;
    |-- uchar* ptr; // data pointer for an unsigned char matrix
    |-- short* s; // data pointer for a short matrix
    |-- int* i; // data pointer for an integer matrix
    |-- float* fl; // data pointer for a float matrix
    |-- double* db; // data pointer for a double matrix


    CvMatND // N-dimensional array
    |-- int type; // elements type (uchar,short,int,float,double) and flags
    |-- int dims; // number of array dimensions
    |-- union data;
    | |-- uchar* ptr; // data pointer for an unsigned char matrix
    | |-- short* s; // data pointer for a short matrix
    | |-- int* i; // data pointer for an integer matrix
    | |-- float* fl; // data pointer for a float matrix
    | |-- double* db; // data pointer for a double matrix
    |
    |-- struct dim[]; // information for each dimension
    |-- size; // number of elements in a given dimension
    |-- step; // distance between elements in a given dimension


    CvSparseMat // SPARSE N-dimensional array

  • Generic arrays:
    CvArr*     // Used only as a function parameter to specify that the
    // function accepts arrays of more than a single type, such
    // as: IplImage*, CvMat* or even CvSeq*. The particular array
    // type is determined at runtime by analyzing the first 4
    // bytes of the header of the actual array.

  • Scalars:
    CvScalar
    |-- double val[4]; //4D vector

    Initializer function:

    CvScalar s = cvScalar(double val0, double val1=0, double val2=0, double val3=0);

    Example:

    CvScalar s = cvScalar(20.0);
    s.val[0]=10.0;

    Note that the initializer function has the same name as the data structure only starting with a lower case character. It is not a C++ constructor.

Other data structures

  • Points:
    CvPoint      p = cvPoint(int x, int y);
    CvPoint2D32f p = cvPoint2D32f(float x, float y);
    CvPoint3D32f p = cvPoint3D32f(float x, float y, float z);

    E.g.:
    p.x=5.0;
    p.y=5.0;

  • Rectangular dimensions:
    CvSize       r = cvSize(int width, int height);
    CvSize2D32f r = cvSize2D32f(float width, float height);

  • Rectangular dimensions with offset:
    CvRect       r = cvRect(int x, int y, int width, int height);

Working with images

Allocating and releasing images

  • Allocate an image:
    IplImage* cvCreateImage(CvSize size, int depth, int channels);

    size: cvSize(width,height);

    depth: pixel depth in bits: IPL_DEPTH_8U, IPL_DEPTH_8S, IPL_DEPTH_16U,
    IPL_DEPTH_16S, IPL_DEPTH_32S, IPL_DEPTH_32F, IPL_DEPTH_64F

    channels: Number of channels per pixel. Can be 1, 2, 3 or 4. The channels
    are interleaved. The usual data layout of a color image is
    b0 g0 r0 b1 g1 r1 ...

    Examples:

    // Allocate a 1-channel byte image
    IplImage* img1=cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,1);

    // Allocate a 3-channel float image
    IplImage* img2=cvCreateImage(cvSize(640,480),IPL_DEPTH_32F,3);

  • Release an image:
    IplImage* img=cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,1);
    cvReleaseImage(&img);

  • Clone an image:
    IplImage* img1=cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,1);
    IplImage* img2;
    img2=cvCloneImage(img1);

  • Set/get the region of interest:
    void  cvSetImageROI(IplImage* image, CvRect rect);
    void cvResetImageROI(IplImage* image);
    vRect cvGetImageROI(const IplImage* image);

    The majority of OpenCV functions support ROI.

  • Set/get the channel of interest:
    void cvSetImageCOI(IplImage* image, int coi); // 0=all
    int cvGetImageCOI(const IplImage* image);

    The majority of OpenCV functions do NOT support COI.

Reading and writing images

  • Reading an image from a file:
      IplImage* img=0;
    img=cvLoadImage(fileName);
    if(!img) printf("Could not load image file: %s\n",fileName);

    Supported image formats: BMP, DIB, JPEG, JPG, JPE, PNG, PBM, PGM, PPM,
    SR, RAS, TIFF, TIF

    By default, the loaded image is forced to be a 3-channel color image. This default can be modified by using:

      img=cvLoadImage(fileName,flag);

    flag: >0 the loaded image is forced to be a 3-channel color image
    =0 the loaded image is forced to be a 1 channel grayscale image
    <0>

  • Writing an image to a file:
      if(!cvSaveImage(outFileName,img)) printf("Could not save: %s\n",outFileName);

    The output file format is determined based on the file name extension.

Accessing image elements

  • Assume that you need to access the $k$-th channel of the pixel at the $i$-row and $j$-th column. The row index $i$ is in the range $[0,\mbox{height}-1]$. The column index $j$ is in the range $[0,\mbox{width}-1]$. The channel index $k$ is in the range $[0,\mbox{nchannels}-1]$.

  • Indirect access: (General, but inefficient, access to any type image)

    • For a single-channel byte image:
      IplImage* img=cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,1);
      CvScalar s;
      s=cvGet2D(img,i,j); // get the (i,j) pixel value
      printf("intensity=%f\n",s.val[0]);
      s.val[0]=111;
      cvSet2D(img,i,j,s); // set the (i,j) pixel value

    • For a multi-channel float (or byte) image:
      IplImage* img=cvCreateImage(cvSize(640,480),IPL_DEPTH_32F,3);
      CvScalar s;
      s=cvGet2D(img,i,j); // get the (i,j) pixel value
      printf("B=%f, G=%f, R=%f\n",s.val[0],s.val[1],s.val[2]);
      s.val[0]=111;
      s.val[1]=111;
      s.val[2]=111;
      cvSet2D(img,i,j,s); // set the (i,j) pixel value

  • Direct access: (Efficient access, but error prone)

    • For a single-channel byte image:
      IplImage* img=cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,1);
      ((uchar *)(img->imageData + i*img->widthStep))[j]=111;

    • For a multi-channel byte image:
      IplImage* img=cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,3);
      ((uchar *)(img->imageData + i*img->widthStep))[j*img->nChannels + 0]=111; // B
      ((uchar *)(img->imageData + i*img->widthStep))[j*img->nChannels + 1]=112; // G
      ((uchar *)(img->imageData + i*img->widthStep))[j*img->nChannels + 2]=113; // R

    • For a multi-channel float image:
      IplImage* img=cvCreateImage(cvSize(640,480),IPL_DEPTH_32F,3);
      ((float *)(img->imageData + i*img->widthStep))[j*img->nChannels + 0]=111; // B
      ((float *)(img->imageData + i*img->widthStep))[j*img->nChannels + 1]=112; // G
      ((float *)(img->imageData + i*img->widthStep))[j*img->nChannels + 2]=113; // R

  • Direct access using a pointer: (Simplified and efficient access under limiting assumptions)

    • For a single-channel byte image:
      IplImage* img  = cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,1);
      int height = img->height;
      int width = img->width;
      int step = img->widthStep/sizeof(uchar);
      uchar* data = (uchar *)img->imageData;
      data[i*step+j] = 111;

    • For a multi-channel byte image:
      IplImage* img  = cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,3);
      int height = img->height;
      int width = img->width;
      int step = img->widthStep/sizeof(uchar);
      int channels = img->nChannels;
      uchar* data = (uchar *)img->imageData;
      data[i*step+j*channels+k] = 111;

    • For a multi-channel float image (assuming a 4-byte alignment):
      IplImage* img  = cvCreateImage(cvSize(640,480),IPL_DEPTH_32F,3);
      int height = img->height;
      int width = img->width;
      int step = img->widthStep/sizeof(float);
      int channels = img->nChannels;
      float * data = (float *)img->imageData;
      data[i*step+j*channels+k] = 111;

  • Direct access using a c++ wrapper: (Simple and efficient access)

    • Define a c++ wrapper for single-channel byte images, multi-channel byte images, and multi-channel float images:
      template class Image
      {
      private:
      IplImage* imgp;
      public:
      Image(IplImage* img=0) {imgp=img;}
      ~Image(){imgp=0;}
      void operator=(IplImage* img) {imgp=img;}
      inline T* operator[](const int rowIndx) {
      return ((T *)(imgp->imageData + rowIndx*imgp->widthStep));}
      };

      typedef struct{
      unsigned char b,g,r;
      } RgbPixel;

      typedef struct{
      float b,g,r;
      } RgbPixelFloat;

      typedef Image RgbImage;
      typedef Image RgbImageFloat;
      typedef Image BwImage;
      typedef Image BwImageFloat;

    • For a single-channel byte image:
      IplImage* img=cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,1);
      BwImage imgA(img);
      imgA[i][j] = 111;

    • For a multi-channel byte image:
      IplImage* img=cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,3);
      RgbImage imgA(img);
      imgA[i][j].b = 111;
      imgA[i][j].g = 111;
      imgA[i][j].r = 111;

    • For a multi-channel float image:
      IplImage* img=cvCreateImage(cvSize(640,480),IPL_DEPTH_32F,3);
      RgbImageFloat imgA(img);
      imgA[i][j].b = 111;
      imgA[i][j].g = 111;
      imgA[i][j].r = 111;

Image conversion

  • Convert to a grayscale or color byte-image:
    cvConvertImage(src, dst, flags=0);

    src = float/byte grayscale/color image
    dst = byte grayscale/color image
    flags = CV_CVTIMG_FLIP (flip vertically)
    CV_CVTIMG_SWAP_RB (swap the R and B channels)

  • Convert a color image to grayscale:


    Using the OpenCV conversion:

    cvCvtColor(cimg,gimg,CV_BGR2GRAY); // cimg -> gimg


    Using a direct conversion:

    for(i=0;iheight;i++) for(j=0;jwidth;j++)
    gimgA[i][j]= (uchar)(cimgA[i][j].b*0.114 +
    cimgA[i][j].g*0.587 +
    cimgA[i][j].r*0.299);

  • Convert between color spaces:

    cvCvtColor(src,dst,code); // src -> dst

    code = CV_2
    / = RGB, BGR, GRAY, HSV, YCrCb, XYZ, Lab, Luv, HLS

    e.g.: CV_BGR2GRAY, CV_BGR2HSV, CV_BGR2Lab

Drawing commands

  • Draw a box:
    // draw a box with red lines of width 1 between (100,100) and (200,200)
    cvRectangle(img, cvPoint(100,100), cvPoint(200,200), cvScalar(255,0,0), 1);

  • Draw a circle:
    // draw a circle at (100,100) with a radius of 20. Use green lines of width 1
    cvCircle(img, cvPoint(100,100), 20, cvScalar(0,255,0), 1);

  • Draw a line segment:
    // draw a green line of width 1 between (100,100) and (200,200)
    cvLine(img, cvPoint(100,100), cvPoint(200,200), cvScalar(0,255,0), 1);

  • Draw a set of polylines:
    CvPoint  curve1[]={10,10,  10,100,  100,100,  100,10};
    CvPoint curve2[]={30,30, 30,130, 130,130, 130,30, 150,10};
    CvPoint* curveArr[2]={curve1, curve2};
    int nCurvePts[2]={4,5};
    int nCurves=2;
    int isCurveClosed=1;
    int lineWidth=1;

    cvPolyLine(img,curveArr,nCurvePts,nCurves,isCurveClosed,cvScalar(0,255,255),lineWidth);

  • Draw a set of filled polygons:
    cvFillPoly(img,curveArr,nCurvePts,nCurves,cvScalar(0,255,255));

  • Add text:
    CvFont font;
    double hScale=1.0;
    double vScale=1.0;
    int lineWidth=1;
    cvInitFont(&font,CV_FONT_HERSHEY_SIMPLEX|CV_FONT_ITALIC, hScale,vScale,0,lineWidth);

    cvPutText (img,"My comment",cvPoint(200,400), &font, cvScalar(255,255,0));

    Other possible fonts:

    CV_FONT_HERSHEY_SIMPLEX, CV_FONT_HERSHEY_PLAIN,
    CV_FONT_HERSHEY_DUPLEX, CV_FONT_HERSHEY_COMPLEX,
    CV_FONT_HERSHEY_TRIPLEX, CV_FONT_HERSHEY_COMPLEX_SMALL,
    CV_FONT_HERSHEY_SCRIPT_SIMPLEX, CV_FONT_HERSHEY_SCRIPT_COMPLEX,

Working with matrices

Allocating and releasing matrices

  • General:
    • OpenCV has a C interface to matrix operations. There are many alternatives that have a C++ interface (which is more convenient) and are as efficient as OpenCV.
    • Vectors are obtained in OpenCV as matrices having one of their dimensions as 1.
    • Matrices are stored row by row where each row has a 4 byte alignment.

  • Allocate a matrix:
    CvMat* cvCreateMat(int rows, int cols, int type);

    type: Type of the matrix elements. Specified in form
    CV_(S|U|F)C. E.g.: CV_8UC1 means an
    8-bit unsigned single-channel matrix, CV_32SC2 means a 32-bit signed
    matrix with two channels.

    Example:
    CvMat* M = cvCreateMat(4,4,CV_32FC1);

  • Release a matrix:
    CvMat* M = cvCreateMat(4,4,CV_32FC1);
    cvReleaseMat(&M);

  • Clone a matrix:
    CvMat* M1 = cvCreateMat(4,4,CV_32FC1);
    CvMat* M2;
    M2=cvCloneMat(M1);

  • Initialize a matrix:
    double a[] = { 1,  2,  3,  4,
    5, 6, 7, 8,
    9, 10, 11, 12 };

    CvMat Ma=cvMat(3, 4, CV_64FC1, a);

    Alternatively:

    CvMat Ma;
    cvInitMatHeader(&Ma, 3, 4, CV_64FC1, a);

  • Initialize a matrix to identity:
    CvMat* M = cvCreateMat(4,4,CV_32FC1);
    cvSetIdentity(M); // does not seem to be working properly

Accessing matrix elements

  • Assume that you need to access the $(i,j)$ cell of a 2D float matrix.

  • Indirect matrix element access:
    cvmSet(M,i,j,2.0); // Set M(i,j)
    t = cvmGet(M,i,j); // Get M(i,j)

  • Direct matrix element access assuming a 4-byte alignment:
    CvMat* M    = cvCreateMat(4,4,CV_32FC1);
    int n = M->cols;
    float *data = M->data.fl;

    data[i*n+j] = 3.0;

  • Direct matrix element access assuming possible alignment gaps:
    CvMat* M    = cvCreateMat(4,4,CV_32FC1);
    int step = M->step/sizeof(float);
    float *data = M->data.fl;

    (data+i*step)[j] = 3.0;

  • Direct matrix element access of an initialized matrix:
    double a[16];
    CvMat Ma = cvMat(3, 4, CV_64FC1, a);
    a[i*4+j] = 2.0; // Ma(i,j)=2.0;

Matrix/vector operations

  • Matrix-matrix operations:
    CvMat *Ma, *Mb, *Mc;
    cvAdd(Ma, Mb, Mc); // Ma+Mb -> Mc
    cvSub(Ma, Mb, Mc); // Ma-Mb -> Mc
    cvMatMul(Ma, Mb, Mc); // Ma*Mb -> Mc

  • Elementwise matrix operations:
    CvMat *Ma, *Mb, *Mc;
    cvMul(Ma, Mb, Mc); // Ma.*Mb -> Mc
    cvDiv(Ma, Mb, Mc); // Ma./Mb -> Mc
    cvAddS(Ma, cvScalar(-10.0), Mc); // Ma.-10 -> Mc

  • Vector products:
    double va[] = {1, 2, 3};
    double vb[] = {0, 0, 1};
    double vc[3];

    CvMat Va=cvMat(3, 1, CV_64FC1, va);
    CvMat Vb=cvMat(3, 1, CV_64FC1, vb);
    CvMat Vc=cvMat(3, 1, CV_64FC1, vc);

    double res=cvDotProduct(&Va,&amp;Vb); // dot product: Va . Vb -> res
    cvCrossProduct(&Va, &amp;Vb, &Vc); // cross product: Va x Vb -> Vc
    end{verbatim}

    Note that Va, Vb, Vc, must be 3 element vectors in a cross product.


  • Single matrix operations:
    CvMat *Ma, *Mb;
    cvTranspose(Ma, Mb); // transpose(Ma) -> Mb (cannot transpose onto self)
    CvScalar t = cvTrace(Ma); // trace(Ma) -> t.val[0]
    double d = cvDet(Ma); // det(Ma) -> d
    cvInvert(Ma, Mb); // inv(Ma) -> Mb

  • Inhomogeneous linear system solver:
    CvMat* A  = cvCreateMat(3,3,CV_32FC1);
    CvMat* x = cvCreateMat(3,1,CV_32FC1);
    CvMat* b = cvCreateMat(3,1,CV_32FC1);
    cvSolve(&A, &amp;b, &x); // solve (Ax=b) for x

  • Eigen analysis (of a symmetric matrix):
    CvMat* A  = cvCreateMat(3,3,CV_32FC1);
    CvMat* E = cvCreateMat(3,3,CV_32FC1);
    CvMat* l = cvCreateMat(3,1,CV_32FC1);
    cvEigenVV(&A, &amp;E, &l); // l = eigenvalues of A (descending order)
    // E = corresponding eigenvectors (rows)

  • Singular value decomposition:
    CvMat* A  = cvCreateMat(3,3,CV_32FC1);
    CvMat* U = cvCreateMat(3,3,CV_32FC1);
    CvMat* D = cvCreateMat(3,3,CV_32FC1);
    CvMat* V = cvCreateMat(3,3,CV_32FC1);
    cvSVD(A, D, U, V, CV_SVD_U_T|CV_SVD_V_T); // A = U D V^T

    The flags cause U and V to be returned transposed (does not work well without the transpose flags).

Working with video sequences

Capturing a frame from a video sequence

  • OpenCV supports capturing images from a camera or a video file (AVI).

  • Initializing capture from a camera:
    CvCapture* capture = cvCaptureFromCAM(0); // capture from video device #0

  • Initializing capture from a file:
    CvCapture* capture = cvCaptureFromAVI("infile.avi");

  • Capturing a frame:
    IplImage* img = 0;
    if(!cvGrabFrame(capture)){ // capture a frame
    printf("Could not grab a frame\n\7");
    exit(0);
    }
    img=cvRetrieveFrame(capture); // retrieve the captured frame

    To obtain images from several cameras simultaneously, first grab an image from each camera. Retrieve the captured images after the grabbing is complete.

  • Releasing the capture source:
    cvReleaseCapture(&capture);

    Note that the image captured by the device is allocated/released by the capture function. There is no need to release it explicitly.

Getting/setting frame information

  • Get capture device properties:
    cvQueryFrame(capture); // this call is necessary to get correct
    // capture properties
    int frameH = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
    int frameW = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
    int fps = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FPS);
    int numFrames = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_COUNT);

    The total frame count is relevant for video files only. It does not seem to be working properly.

  • Get frame information:
    float posMsec   =       cvGetCaptureProperty(capture, CV_CAP_PROP_POS_MSEC);
    int posFrames = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_POS_FRAMES);
    float posRatio = cvGetCaptureProperty(capture, CV_CAP_PROP_POS_AVI_RATIO);

    Get the position of the captured frame in [msec] with respect to the first frame, or get its index where the first frame starts with an index of 0. The relative position (ratio) is 0 in the first frame and 1 in the last frame. This ratio is valid only for capturing images from a file.

  • Set the index of the first frame to capture:
    // start capturing from a relative position of 0.9 of a video file
    cvSetCaptureProperty(capture, CV_CAP_PROP_POS_AVI_RATIO, (double)0.9);

    This only applies for capturing from a file. It does not seem to be working properly.

Saving a video file

  • Initializing a video writer:
    CvVideoWriter *writer = 0;
    int isColor = 1;
    int fps = 25; // or 30
    int frameW = 640; // 744 for firewire cameras
    int frameH = 480; // 480 for firewire cameras
    writer=cvCreateVideoWriter("out.avi",CV_FOURCC('P','I','M','1'),
    fps,cvSize(frameW,frameH),isColor);

    Other possible codec codes:

    CV_FOURCC('P','I','M','1')    = MPEG-1 codec
    CV_FOURCC('M','J','P','G') = motion-jpeg codec (does not work well)
    CV_FOURCC('M', 'P', '4', '2') = MPEG-4.2 codec
    CV_FOURCC('D', 'I', 'V', '3') = MPEG-4.3 codec
    CV_FOURCC('D', 'I', 'V', 'X') = MPEG-4 codec
    CV_FOURCC('U', '2', '6', '3') = H263 codec
    CV_FOURCC('I', '2', '6', '3') = H263I codec
    CV_FOURCC('F', 'L', 'V', '1') = FLV1 codec

    A codec code of -1 will open a codec selection window (in windows).

  • Writing the video file:
    IplImage* img = 0;
    int nFrames = 50;
    for(i=0;i

    To view the captured frames during capture, add the following in the loop:

    cvShowImage("mainWin", img);
    key=cvWaitKey(20); // wait 20 ms

    Note that without the 20[msec] delay the captured sequence is not displayed properly.

  • Releasing the video writer:
    cvReleaseVideoWriter(&writer);


next_inactive up previous
Gady Agam 2006-03-31

Installing OpenCV from CVS on Ubuntu Edgy

The following is from:

http://www.ryanbruce.org/
very good instruction.

Installing OpenCV from CVS on Ubuntu Edgy

November 30th, 2006 by ryanmbruce

These are my notes concerning the installation of OpenCV from CVS on Ubuntu Edgy. While I’ll try to be helpful if you have problems, I’m not responsible for blowing up your system.

The charade:
Check out the OpenCV code from cvs:

cvs -d:pserver:anonymous@opencvlibrary.cvs.sourceforge.net:/cvsroot/opencvlibrary login
cvs -z3 -d:pserver:anonymous@opencvlibrary.cvs.sourceforge.net:/cvsroot/opencvlibrary co -P opencv

Then make sure pkg-config and g++ are installed:

sudo apt-get install g++ pkg-config

At this point, you should be able to configure and install opencv, but it probably won’t find some of the libraries it needs to work with video and certain image formats. To get all the functionality of OpenCV, I installed the following packages (Some of these are in the multiverse repositories. Go here to find out how to add more repositories):

sudo apt-get install libgtk2.0-dev libavcodec-dev libavformat-dev libjpeg62-dev libtiff4-dev

Now you can run:

cd opencv && ./configure

Check to make sure all of the fancy features you want show up as enabled. The packages we installed earlier make my configuration show up something like so:

General configuration =============================================
Compiler: g++
CXXFLAGS: -Wall -fno-rtti -pipe -O3 -g -march=i686 -ffast-math -fomit-frame-pointer
Install path: /usr/local

HighGUI configuration =============================================

Windowing system --------------
Use Carbon / Mac OS X: no
Use gtk+ 2.x: yes
Use gthread: yes

Image I/O ---------------------
Use libjpeg: yes
Use zlib: yes
Use libpng: yes
Use libtiff: yes
Use libjasper: no
Use libIlmImf: no

Video I/O ---------------------
Use QuickTime / Mac OS X: no
Use xine: no
Use ffmpeg: yes
Use dc1394 & raw1394: yes
Use v4l: yes
Use v4l2: yes

Wrappers for other languages =========================================
SWIG
Python no

Additional build settings ============================================
Build demo apps yes

Now run make ...

If everything looks good, we can now compile and install OpenCV:

make && sudo make install && sudo ldconfig

You may need to run the following command if /usr/local isn’t in your library search path (make sure you trust users who have write access to /usr/local/lib):

sudo sh -c 'echo "/usr/local/lib" >> /etc/ld.so.conf && ldconfig'

Instead, some guides may instruct you to change the LD_LIBRARY_PATH environment variable, but this is not the best way to get your programs to work. Modifying this variable is generally used as a hack to get things working in the moment, but it should not be used as a permanent solution, as it poses security problems. This means that you shouldn’t try setting this variable in any startup scripts… See this page about shared libraries.

Now you can start writing programs which employ the functionality of OpenCV. The best way learn how to do this is by looking at the sample applications. You can compile the sample applications by doing the following:

cd samples/c
chmod u+x build_all.sh
./build_all.sh

Now you can run the sample apps just like any other executable:

./ProgramName --ProgramOptions

Please comment if you find problems or have suggestions.

Troubleshooting:
If you get an error like the following one after running your application, then you didn’t correctly add /usr/local/lib to the library search path. Go back and do it correctly…

./ProgramName: error while loading shared libraries:
libcxcore.so.1: cannot open shared object file: No such file or directory

Links:
http://www.hci.iastate.edu/575x/doku.php
The wiki for a class using OpenCV. There are examples, tutorials, problems, and students’ solutions all open to the public.

http://opencvlibrary.sourceforge.net
The official OpenCV wiki.

5/3/07

install dwww.

dwww is very good. It will search the documents in the system (not a search engine) and make it very easy to find the help or manuals.

5/2/07

change apt-get default archives directory.

In /etc/apt/, edit a file apt.conf if it doesn't exist. In this file add the following:
Dir::Cache::archives "the/location/you/want/" ;
do not forget ;
In the director you want you must have similar lay out of directory. for example
/home/user/var/cache/apt/archives/
in the above directory you must have partial(director) also.
You can use the following to make the directory:
mkdir -p /home/user/var/cache/apt/archives/partial/
Then your apt.conf can be the following:

Dir::Cache::archives "/home/user/var/cache/apt/archives/";

Another way is:
aptitude -o Dir::Cache::archives "/home/user/var/cache/apt/archives/"
I did not try this one, though it is supposed to work.

4/23/07

C++ currying.

http://www.numerical-recipes.com/forum/showthread.php?t=526

NR and extra parameters.

http://www.thescripts.com/forum/thread509195.html

4/21/07

image zoomin.

When zoom in the image, the number of pixels occupied by the objects increases. I think there is some interpolations!!

4/14/07

source navigator

It is a very nice tool for source/code reading.

4/13/07

sort two vectors.

cvcl-20060527/src/include/cvclutil.h - Google Code Search
sort one vector based on the other.

template
std::pair strPair(const std::string& f, const T& t) {
return std::pair(f, t);
}

typedef std::pair StrPair;

//! Sort two vectors based on the first vector
template
void sort2(std::vector& keys, std::vector& vals) {
DebugAssert(keys.size()==vals.size(), "sort2()");
// Create std::vector of pairs std::vector > pairs;
for(size_t i=0, iend=keys.size(); i pairs.push_back(strPair(keys[i], vals[i]));
// Sort pairs
StrPairLess comp;
sort(pairs.begin(), pairs.end(), comp);
DebugAssert(pairs.size() == keys.size(), "sort2()");
// Split the pairs back into the original vectors
for(size_t i=0, iend=pairs.size(); i keys[i] = pairs[i].first;
vals[i] = pairs[i].second;
}
}

}

4/12/07

using magick++

c++ -o example example.cpp `Magick++-config --cppflags --cxxflags --ldflags --libs`


Now I want to use kdevelop as my IDE and use Qmake. How to use magick++ library now?
1. in a console type:
>
Magick++-config --cppflags --cxxflags --ldflags --libs

-I/usr/include
-pthread
-L/usr/lib -L/usr/X11R6/lib -lfreetype -lz -L/usr/lib
-lMagick++ -lWand -lMagick -llcms -ltiff -lfreetype -ljasper -ljpeg -lpng -ldpstk -ldps -lXext -lXt -lSM -lICE -lX11 -lbz2 -lxml2 -lz -lpthread -lm -lpthread

The above is the output.
So in the src. pro file, add the following:

INCLUDEPATH += /usr/include /usr/include/magick

LIBS = -lfreetype -lz -lMagick++ -lWand -lMagick -llcms -ltiff -lfreetype -ljasper -ljpeg -lpng -ldpstk -ldps -lXext -lXt -lSM -lICE -lX11 -lbz2 -lxml2 -lz -lpthread -lm -lpthread


Now recompile the project. It should work.

MTL installation.

copy the mtl folder which contains all the header files to /usr/include/
e.g:
cp -R /xxx/mtl /usr/local/
After that, make sure that when include these headers, using the following:
#include "mtl/matrix.h"
must have the mtl/, otherwise can not find them.

4/11/07

nice

nice -19 jigdo-lite debian-40r0-i386-DVD-1.jigdo

this will set the jigdo-lite's priority to minimum.

4/9/07

compile matlab m files.

mcc -x file.m
this will not generate stand-alone, but it does accelerate the speed very much.

4/3/07

How to Open a Program Automatically When a Mac Starts Up

How to Open a Program Automatically When a Mac Starts Up

Rate This Article:
Difficulty: Easy
If you use a particular program or application every time you start up your Mac, here is how to make it launch itself. You can also make a sound play automatically this way.

Instructions

  • STEP 1: Find the application (or sound) icon and click on it.
  • STEP 2: Click on the File menu and select Make Alias.
  • STEP 3: Drag the alias to the desktop where you can get at it.
  • STEP 4: Double-click to open the System Folder and locate the Startup Items folder.
  • STEP 5: Drop the alias into the Startup Items folder. The next time you start up your Mac, the application will launch.


3/15/07

print double side.

lpoptions -p printer_name -l
the above will display all the options for help. And the final command is:
lpoptions -p printer_name -o Duplex=DuplexNoTumble

3/2/07

start GUI windows using root account.

Usually I did is to start a terminal, su to root account and then start the GUI window. Another way to do is:
1. click the K menu.
2. click "run command..."
3. input "kdesu kate" for example, then you will be asked to input root's password.

3/1/07

Change default x window manager.

How to change the default window manager (KDE, Gnome, etc.) in Debian "Sarge":

Symlinks in /etc/alternatives point to various "default" programs (as far as Debian is concerned).

The one you're looking for is /etc/alternatives/x-session-manager

You can also use `/usr/sbin/update-alternatives --config x-session-manager`.

To change the default display manager (the program that presents the login screen) to KDE,
install kdm using `apt-get install kdm` and it should ask you which display manager you want to be the default.

From here


What I did is the following, since I already installed kdm and gdm before. I can not automatically start kdm. So I did the following:
# /usr/sbin/update-alternatives --config x-session-manager

There are 4 alternatives which provide `x-session-manager'.

Selection Alternative
-----------------------------------------------
*+ 1 /usr/bin/gnome-session
2 /usr/bin/startkde
3 /usr/bin/icewm-session
4 /usr/bin/xfce4-session

Press enter to keep the default[*], or type selection number: 2
Using `/usr/bin/startkde' to provide `x-session-manager'.


After this, I still cannot start kdm automatically.

Sysv-rc-conf

From Wiki

sysv-rc-conf - Run level configurator (front-end) for init.d scripts (Debian)

apt-get install sysv-rc-conf

To Run, type in:

sysv-rc-conf

A graphical list of all items stored in /etc/init.d/ will be listed. Items placed in this directory must be given a run-level.



I run

sysv-rc-conf

and found that kdm is not run under run level 4 which is the run level I used. So I check kdm up, and try.


2/28/07

Switch between gdm and kdm.

Open a terminal window and type in the following command:

dpkg-reconfigure gdm

/etc/hosts.allow and hosts.deny

when I did nvidia update, the screen always has problem, showing inbound etc. What I did is to stop guarddog.
In the Guarddog, there is a tab "loging", where you can change how often the inbound or outbound is written to the system log file.

Stop Xserver to install Nvidia driver.

If you are using NVdia card, you will have this problem. When you need to update the driver, you need to stop the Xserver before you do it. Here is how you can do it.
1.

/etc/init.d/[gkx]dm stop


whether you use gdm stop or kdm stop or xdm stop depends on what you are using. You need to be root in order to do this.

2. Now you can update your Nvidia driver. Usually you do it like the following:

nvidia-installer --update

Mac fink installation.

On Mac I installed fink. It is very good. I installed xfig, and latex using fink. However I spent quite a while try to find where those exec files are. It turned out that most of the files are in the folder: /sw/bin/

2/27/07

On Mac use Keynote to prepare big posters.

Setup the page size correctly:

First generate an empty page, then go to the inspector. Select the first tab, then click the slide size drop-down and pick “Custom Slide Size”. Keynote assumes 72 pixels per inch, so multiply your desired poster size by 72 and enter that for the slide size height and width. Personally for my poster (44 inch x 36 inch), the numbers are: (3168x2592).

Note that Keynote will insert a white margin around your poster when you go to print it, so you don’t need to put a border around things when designing your poster. You can put objects right up to the very edge of the slide and they will still print OK.

2/24/07

suse yast source

http://en.opensuse.org/YaST_Software_Management

2/16/07

Using C++ to read a tab seperated Matlab matrix

#include <iostream>
#include <istream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <iterator>
#include <algorithm> // for copy

using namespace std;

// template <class T>
// std::vector<T> StringToVec( const std::string& Str );
// Tokenize a passed line/string into a vector
// e.g:
// std::string str = "1 2 3 4";
// std::vector<int> vec = StringToVector<int>(str);

template <class T>
vector<T> StringToVec( const string &str )
{
vector<T> MyVec;
istringstream iss (str, istringstream::in);
copy(istream_iterator<T>(iss), istream_iterator<T>(), back_inserter(MyVec)); //check http://www.sgi.com/tech/stl/istream_iterator.html
return MyVec;
}

The following use the above template to read in a big matrix from a file. Using C++ to read big matrix from a file, need the above code.


int main()
{
vector< vector<float> > Matrix;
vector<float> Row;
string Line;
ifstream in("./test.dat");
if( !in ) {
cerr << "can't open file" << endl;
return false;
}

// read matrix row's
while( getline( in, Line) ) {
Row = StringToVec<float>( Line );
Matrix.push_back( Row );
Row.clear();
}

// output the matrix
for( vector< vector<float> >::iterator IterRow = Matrix.begin(); IterRow !=
Matrix.end(); ++IterRow ) {
for( vector<float>::iterator IterCol = IterRow->begin(); IterCol !=
IterRow->end(); ++IterCol ) {
cout << *IterCol << " ";
}
cout << endl;
}

return 1;

}

2/13/07

Matlab no GUI.

he first "Solution" practically worked for me with:

export LD_ASSUME_KERNEL=2.4.1

to the effect that the matlab window now pops up and remains, though the fonts seem to be a little too big...

2/8/07

install gfortran from source file.

On Wed, Sep 21, 2005 at 06:09:52PM -0400, Prof J C Nash wrote:
> In trying to install gfortran I note that the installation instructions
> link leads to a blank page. Is there a good link please? (Linux install,
> specifically Debian for Xandros 3.02.
>

John,

To build gfortran from the gcc source distribution on linux
should be fairly straigth forward.

(1) Get gcc-4.0.1.tar.gz (see gcc.gnu.org)
Note 4.0.2 will be released in the next few days, and you'll
definitely want 4.0.2 over 4.0.1.
(2) Unpack.
cd tmp
tar xzf /path/to/gcc-4.0.1.tar.gz
(3) To build gfortran
mkdir obj
cd obj
../gcc-4.0.1/configure --enable-languages='c,fortran'
make bootstrap
(4) Install gfortran
make install
(5) Try buildling your software. Send bug reports.

Note, this will put gfortran under /usr/local/ if you want a
different directory use --prefix=/path/to/gfortran with configure.

--enable-languages=lang1,lang2,...
Specify that only a particular subset of compilers and their runtime libraries should be built. For a list of valid values for langN you can issue the following command in the gcc directory of your GCC source tree:
grep language= */config-lang.in

Currently, you can use any of the following: all, ada, c, c++, fortran, java, objc, obj-c++, treelang. Building the Ada compiler has special requirements, see below. If you do not pass this flag, or specify the option all, then all default languages available in the gcc sub-tree will be configured. Ada, Objective-C++, and treelang are not default languages; the rest are. Re-defining LANGUAGES when calling `make bootstrap' does not work anymore, as those language sub-directories might not have been configured!



Here are binary files for Mac.

http://gcc.gnu.org/wiki/GFortranBinaries

2/7/07

Backup data under linux.

We just got the 500G external hard drive. The task is to backup the data in the linux system, mainly the research data.
First tried the following scripts:

#!/bin/bash
CurDate=`date +"%m%d%y"`
tar --verify -cf /media/usbdisk2/username/linuxbk/home_$CurDate.monthlyfull.tar /home/username/

However, there was an error, saying that "8811 File size limit exceeded". Then I searched the website and find the following solution by using split.

#!/bin/bash
CurDate=`date +"%m%d%y"`
tar cPf - /home/username/|(cd /media/usbdisk2/username/linuxbk/; split --verbose --bytes=1000m - home_$CurDate.monthlyfull.tar)

Here I split the cells by 1 G. This does work and there is no error on this. Now the question is how to recover this if necessary.

cat /media/usbdisk2/username/linuxbk/home_$CurDate.monthlyfull.tar* | tar xvf - {/home/{{dirs}/files}}

"You can cat from anywhere since you used the "P" tar option which preserves the root "? Here maybe it is better not to use "P" option, because that may overwrite the username home directory when restore it.


1/24/07

Speed up openoffice

This is something that I usually do as a post install tweak. I have 512+ plus RAM systems that work well with this, although I have noticed *speedier* results with 256 mb RAM.

Applications-->OpenOffice.org Writer-->Tools-->Options

Under the OpenOffice.org heading, select Memory

Under Graphics Cache change the "Use for OpenOffice.org" to 30 MB
Change "Memory per Object" to 2.0 MB

Close OpenOffice.org

Restart OpenOffice and marvel at the speed!!!

Your mileage may vary, consult your doctor before begining any physical exercise program.

Please note this is my first howto. I have tried to follow the howto format as best I can. Please give me any feedback you see fit.

problem with the apt-get upgrade.

Use the following command (need root account) to correct this:

dpkg --configure -a

1/22/07

Openoffice formula editor.

I set up shift+space as the shortcut for formula insertion.
Need to show how!!!!!!!!!!!

11/25/06

Mac disk utility--backup the hard drive.

Disk Utility's hidden talents

Working Mac

Poor Disk Utility. It seems fated to remain one of Mac OS X’s most underappreciated utilities. If you’ve even launched it at all, chances are you haven’t gone beyond using its First Aid features to repair a disk (see Mac OS X First Aid). But that merely scratches the surface of what this multitalented tool can do. Here are eight more ways to put Disk Utility to work.

1. Mount and unmount volumes

Most of the time, mounting and ejecting external drives and disks just works. But every now and then, a drive will refuse to mount, or you might eject a connected drive (Command-E) and find yourself puzzled about how to remount it.

PICTURES

click to see larger image

July Working Mac

Gone for Good: When you want to erase a disk and ensure that every scrap of information on it is really gone, use one of these Disk Utility options.

This is when Disk Utility (/Applications/Utilities) is handy to have around. Launch it, and you’ll see all connected but unmounted drives listed in the column on the left of its window. Select the desired volume and click on the Mount button in the toolbar, and your drive is back in action. Another advantage of Disk Utility is that you can use it to eject particular drive partitions. With the Finder, you must eject either all of a drive’s partitions or none of them.

2. Erase a CD-RW/DVD-RW disc

While write-once CDs and DVDs are the most common types of blank discs, there may be times when you work with rewritable (RW) discs. If so, you’ll eventually want to erase the contents of these discs so you can write new data to them. You don’t need add-on software to get this job done. Launch Disk Utility, select the disc from the left column, choose the Erase tab, and then click on Erase in the window that appears.

3. Completely erase a drive

Whether you’re selling your old computer or cleaning out your virtual desk before moving to another job, sometimes you want to erase everything that’s on your hard drive. Disk Utility gives you two options.

The quick and easy way is to select a volume, choose the Erase tab, and click on the Erase button. The disk will now appear empty, even though your data is actually still there. What’s gone is the catalog directory, or the “pointers,” to the files. Your Mac now considers the space free and will write over the data as new information is added.

It’s not easy to access files erased in this way, but a knowledgeable hacker (or a disk-recovery service) could ferret them out. So if you want to make sure that all existing data is truly gone, click on Security Options instead. In this sheet, Disk Utility gives you a number of erasure options, including Zero Out Data, 7-Pass Erase, and 35-Pass Erase. When you select multiple passes, the drive is erased multiple times to remove all data traces. But be aware that more passes take more time. Unless you work for the CIA, the Zero Out Data option (which is one pass) should be sufficient (see screenshot).

If you’re concerned that something sensitive you already deleted might still be recoverable but you don’t want to erase the entire drive, never fear. Disk Utility can help in this situation, too. Select the volume, choose the Erase tab, and click on the Erase Free Space button. In the sheet that appears, pick the desired number of erasure passes. Disk Utility targets only files that you’ve deleted, leaving your other files untouched. In the future, you can use the Secure Empty Trash command (Finder: Secure Empty Trash) to thoroughly delete files from the Trash.

4. Partition a drive

Once upon a time, many of us wondered what to do with our colorful iMacs’ whopping 6GB hard drives. But these days, the smallest hard drive you can get with a new iMac is 160GB. With so much space at your disposal, partitioning—splitting up a drive into separate parts—can make a lot of sense. For example, perhaps you want to create two bootable volumes—one for daily use and the other for emergencies or for safely testing new software. (For more reasons to partition, see Multiply Your Drive.)

Launch Disk Utility, select the drive in the left column, and choose the Partition tab. If you’re working with an external drive, click on the Options button and choose the desired option from the Volume Scheme menu. Next, whether you’re using an external or an internal drive, select the number of partitions you want and the size of each one, and give each one a name. Click on the Partition button, and the drive will be erased and reformatted.

5. Create a disk image

Much of the software you download from the Web, especially from Apple, arrives as a disk image (with the telltale file extension .dmg). Double-click on a disk image, and its contents appear on your desktop, almost as if you were mounting an external disk.

Using Disk Utility, you can create image files yourself. Doing so allows you to create a single file that contains an exact duplicate of a given folder’s contents, down to the position of the icons. If you stick with Disk Utility’s default options, the resulting file will also be compressed, so you can save disk space.

To create an image file, launch Disk Utility and select File: New: Disk Image From Folder. In the window that appears, navigate to the desired folder and then click on Image. Give the image file a name, and click on Save when prompted. That’s it.

Another useful aspect of disk images is that you can password-protect them. Select AES-128 from the Encryption pop-up menu in the Save dialog box. This is an easy way to protect important documents on your computer.

6. Burn a bootable duplicate of a disc

Worried about your OS X Install DVD getting damaged, or want a copy to take on a trip? You could burn a copy from the Finder, but you wouldn’t be able to boot from it when you were done. The simple way to create a bootable duplicate is to use Disk Utility to make a disk image and then burn a new disc. (One caveat: Keep in mind that you can’t create a bootable copy of a dual-layer Mac OS X Install DVD if your DVD drive can only record to single-layer DVDs.)

First, launch Disk Utility and mount the CD or DVD. Select the disc from Disk Utility’s left column. Then select File: New: Disk Image From name of disc. A Save dialog box appears. From the Image Format pop-up menu, select DVD/CD Master. Click on Save. After Disk Utility has created the image file, select Images: Burn. In the dialog box that appears, select the image file and click on Burn. Insert a blank disc when prompted.

7. Create a multisession disc

If you take the saying “waste not, want not” to heart, it probably pains you to burn a half-full disc. But did you know that you can record more than once even to so-called “write-once” CDs? You can’t erase what’s already there, but you can keep adding content to a disc until there’s no more free space left. Use Disk Utility to set up the CD as a multisession disc the first time you burn it.

To begin, launch Disk Utility, create an image file of the data you want to burn, and then select Images: Burn. In the dialog box that appears, locate the image file and click on Burn. You are now ready for a crucial step: in the window that appears, select the Leave Disc Appendable option. Click on Burn, and you’re done.

To add more data, you must again use Disk Utility; you cannot add data via the Finder’s Burn command. You can repeat the appending process until the disc is full. When you mount a disc with multiple sessions, each session will mount as a separate volume.

8. Back up a drive

Looking for a free way to back up a drive? Well, you’ve already got one—Disk Utility’s Restore tab. It’s a somewhat crude tool, but it does work. Launch Disk Utility and choose the Restore tab. Next, select the volume you want to back up in the left column, and drag it to the Source text field. Select the volume that will hold the copy, and drag it to the Destination text field.

If you want to erase the contents of the destination volume before storing your backup files there, select the Erase Destination option. Otherwise, the newly stored data is simply added to the existing files. Click on Restore to make a copy, and the backup process is complete. If you need to use your backup files later, simply reverse the Source and Destination directions.

As a bonus, Disk Utility lets you use a disk-image file (created separately via Disk Utility’s New Disk Image command) instead of an actual physical volume as your source. That’s particularly useful if you maintain multiple Macs with a standard preinstalled set of files—in a computer lab, for example. Put your disk image on a portable drive, and then use Disk Utility to restore each Mac to a default state.

[Contributing Editor Ted Landau is the author of Ted Landau’s Mac OS X Help Line: Tiger Edition (Peachpit Press, 2006).]

EDITOR’S NOTE: This story was corrected to reflect that Disk Utility cannot create a multi-session disc with a DVD. We also added a clarification about the need for a DVD burner with dual-layer capabilities to burn dual-layer DVDs.

More from the July 2006 Issue 11 Comments on this story
source from here.

Should also look at "rsync". It seems to be a very nice thing.