Wednesday, January 26, 2011

Trials of pycam example code

I am trying to learn something about computer version, and Python is my first choice of the coding tool. After several hours of searching, I found pycam. There are several sample codes given by the pycam. What I have downloaded was the ``pycam-read-only'' folder in which are three subdirectories:

  • c-vs-py
  • openeyes
  • pycam

To install the pycam, just find the ``setup.py'' in the subdirectory named ``pycam'' and run ``sudo python setup.py install.'' Furthermore, what you need to install might include the follows:

  • python-opencv
  • python-pygame
  • libcv-dev
  • libcvaux-dev
  • libhighgui-dev

The lib*-dev are (my guess) for the cpp codes, which need to include the cv.h and highgui.h.

So far, my testing results are:

  1. pycam-read-only/pycam/examples/: Okay, but the fps are low
  2. pycam-read-only/pycam/examples/opencv: Failed. There were errors I don't know how to resolve yet. Only the ``cam-histo.py'' can be executed, after remove the ``cv.CV_VERSION'' at line 88. (the CV_VERSION seems not in my OpenCV.)
  3. pycam-read-only/pycam/pycam/: Failed
  4. pycam-read-only/c-vs-py/c_examples: Okay
  5. pycam-read-only/c-vs-py/py_examples: Some codes showed errors. They are harris_opencv.py, objectDetect.py, and people_only.py.
---
EDIT: New results are given in the new post:
Trials of pycam example code (2)

    Tuesday, January 25, 2011

    Face detection-- code patch and tests with some drawings

    My colleague introduced me an OpenCV site in Japanese in which many sample codes are available. Most of the sample codes are written in C++, and some are converted to Python also. I copied one sample code, which is used for face detection.

    After testing, I found the sample code has two lines which have to be modified to run properly. The first one seems to be a typo. The variable named as ``storage1'' should be ``storage'' according to other lines of code. The 25th line with variable ``starage1'' should be deleted. Another modification is to change assign the path of Haar-cascade xml files [*] explicitly. The original code gives the xml file without the complete path, and the program cannot find the so-called ``haarcascade_frontalface_default.xml.''

    The patch file:
    @@ -22,9 +22,8 @@
                     sys.exit(-1)
             src_gray = cvCreateImage(cvSize(src_img.width, src_img.height), IPL_DEPTH_8U, 1)
     
    -        storage1 = cvCreateMemStorage(0)
             ## (2)ブーストされた分類器のカスケードを読み込む
    -        cascade_name = "haarcascade_frontalface_default.xml"
    +        cascade_name = "/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml"
             cascade = cvLoadHaarClassifierCascade(cascade_name, cvSize(1,1))
     
             ## (3)メモリを確保し,読み込んだ画像のグレースケール化,ヒストグラムの均一化を行う
    
    


    Here I tested the sample code with some of my drawings, which can be viewed on my another blog. The results are interesting (at least for me).









    ---
    [*] I have just begun to learn things about computer vision, so I might use some terms wrong.

    Thursday, January 13, 2011

    [Py] Spline function test

    To interpolate data points, Scipy has several modules for this work. For what I am interested in, there are two functions seem to meet my requirement:

    According to the explanations given by the above links, to use UnivariateSpline with s=1 is equivalent to use InterpolatedUnivariateSpline.

    Here is the results of a simple test:

    Code:

    from numpy import linspace,exp
    from numpy.random import randn
    from scipy.interpolate import UnivariateSpline, InterpolatedUnivariateSpline
    from pylab import plot, legend, show
    
    x = linspace(-3, 3, 100)
    y = exp(-x**2) + randn(100)/10
    
    s0 = UnivariateSpline(x, y, s=0)
    s1 = UnivariateSpline(x, y, s=1)
    s2 = InterpolatedUnivariateSpline(x, y)
    
    xs = linspace(-3, 3, 1000)
    ys0 = s0(xs)
    ys1 = s1(xs)
    ys2 = s2(xs)
    
    plot(xs,ys0,'g--',label='UnivariateSpline s=0',linewidth=4)
    plot(xs,ys1,'b',label='UnivariateSpline s=1')
    plot(xs,ys2,'k',label='InterpolatedUnivariateSpline')
    plot(x,y,'ro',label='original signal')
    legend()
    show()
    

    Wednesday, January 05, 2011

    Producing sinusoidal signals


    Sometimes I need a signal of different frequencies for testing, so I wrote a simple Python code to produce compound sinusoidal signal by adding several cosine waves of different frequencies, amplitudes, and phases.

    The code is listed as the follows. (download)
    from scipy import *
    from pylab import *
    
    data_size = 10 # number of sinusoidal waves
    
    A = rand(data_size)
    theta = rand(data_size)
    f = [i for i in range(1,data_size+1)]
    t = linspace(0,10,1024)
    
    y = [0.0 for i in range(len(t))]
    
    for i in range(data_size):
            y += A[i]*cos(2*pi*f[i]*t + theta[i])
    
    plot(t,y)
    show()
    

    Trials of EMD C code

    I found a simple module of EMD in C on google code: realtime-emd. The source code, however, has no main function to invoke the modules. So I wrote one as the follows.

    #include <stdio>
    #include "EmpiricalModeDecomposition.h"
    
    void imfs_output(emdData* emd){
            int i, j;
    
            for(j = 0; j < emd->size; j++){
                    for(i = 0; i < emd->order; i++) {
                            printf("%f ", emd->imfs[i][j]);
                    }   
                    printf("\n");
            }   
    }
    
    int main(void){
            FILE *inputfile = fopen("sinusoid.txt","r");
            int i=0;
            float signal[1024]={0.0};
            emdData data;
    
            while (fscanf(inputfile, "%f", &signal[i]) != EOF){
                    //printf("%d %f\n",i,signal[i]);
                    i++;
            }
    
            emdCreate(&data,i,5,10,0); // problems here
            emdDecompose(&data,signal);
            imfs_output(&data);
            emdClear(&data);
    
            fclose(inputfile);
            return 0;
    }
    


    The main problem is the arguments of the function emdCreate. I am not sure how to set proper parameters to obtain correct results, so please take this clip of code as just a reference.

    You can download the main.c and sinusoid.txt for testing. The input file sinusoid.txt was generate by adding several sinusoidal signals.

    Thursday, December 30, 2010

    [QnA] GL/gl.h and GL/glu.h in Ubuntu 10.04

    I have installed PyODE and tried some examples once when my system was Ubuntu 8.04. Today I think about the PyODE examples and want to study them again. Because my system is Ubuntu 10.04 now, I have to rebuild some necessary environment.

    The most tedious step is to install the cgkit. It has to be installed from the source. During the installation, some more packages or libraries are necessary. Two of them are GL/gl.h and GL/glu.h. Out of my expectation, they have to be installed from different packages.

    To have GL/gl.h:

    $ sudo apt-get install mesa-common-dev 

    To have GL/glu.h:

    $ sudo apt-get install libglu1-mesa-dev

    Wednesday, December 22, 2010

    [DP] Window functions trial

    I am studying the windowed-sinc filters and found SciPy has had a set of window functions to play around.

    Below is my code to generate the plot of several window functions. Note that only 12 of them have been shown. There are four of them need more than one argument and I don't have time to figure out their parameters to get corresponding results.
    from scipy import signal
    from pylab import *


    data_point = 500


    windows =\
    ['boxcar'
    , 'triang'
    , 'parzen'
    , 'bohman'
    , 'blackman'
    , 'blackmanharris'
    , 'nuttall'
    , 'flattop'
    , 'bartlett'
    , 'hann'
    , 'barthann'
    , 'hamming'
    #, 'kaiser'
    #, 'gaussian'
    #, 'general_gaussian'
    #, 'slepian'
    ]


    t = [i for i in range(data_point)]
    steps = 3


    for i in range(0,len(windows),steps):
            for j in range(i,i+steps):
                    w = eval('signal.'+windows[j])(data_point)
                    subplot(2,2,1+i/steps)
                    plot(t, w)
                    axis([0,data_point,-0.2,1.2])
            legend((windows[i:i+steps]),loc='upper left')


    show()

    The result:

    Basically, the window functions return an array which has the size as you assigned. An easy example is as the following:

    >>> from scipy import signal
    >>> signal.blackman(50)
    array([ -1.38777878e-17,   1.48858213e-03,   6.05806481e-03,
             1.40095693e-02,   2.58120534e-02,   4.20553960e-02,
             6.33894512e-02,   9.04534244e-02,   1.23800653e-01,
             1.63824257e-01,   2.10689158e-01,   2.64275593e-01,
             3.24138580e-01,   3.89486780e-01,   4.59182958e-01,
             5.31766851e-01,   6.05499812e-01,   6.78429126e-01,
             7.48468603e-01,   8.13490971e-01,   8.71426720e-01,
             9.20363618e-01,   9.58640963e-01,   9.84932919e-01,
             9.98315897e-01,   9.98315897e-01,   9.84932919e-01,
             9.58640963e-01,   9.20363618e-01,   8.71426720e-01,
             8.13490971e-01,   7.48468603e-01,   6.78429126e-01,
             6.05499812e-01,   5.31766851e-01,   4.59182958e-01,
             3.89486780e-01,   3.24138580e-01,   2.64275593e-01,
             2.10689158e-01,   1.63824257e-01,   1.23800653e-01,
             9.04534244e-02,   6.33894512e-02,   4.20553960e-02,
             2.58120534e-02,   1.40095693e-02,   6.05806481e-03,
             1.48858213e-03,  -1.38777878e-17])

    ---
    Ref:
    1. You can find the source code containing these window functions in the SciPy folder. Mine is located in /usr/lib/python2.6/dist-packages/scipy/signal/signaltools.py
    2. Documents can be found at http://docs.scipy.org/doc/scipy/reference/signal.html
    3. There is a good book about the signal processing for engineers by Steven W. Smith: The Scientist and Engineer's Guide to Digital Signal Processing. The windowed-sinc filters are introduced in Chapter 16.

    [ML] Pretty good tutorial for MLE

    What is Maximum Likelihood Estimation (MLE) exactly? This question has bothered me for a long time. When I was reading papers relevant to ICA, the term MLE appeared again. This time, fortunately, I found a really good tutorial in Wikipedia:


    The first three parts introduce the most fundamental ideas about MLE, and I suggest you, who want to figure out what is MLE, to read these three parts.

    In the next three parts, however, some terms and examples seem come from the biology or genetic aspect. If you get confused with the technical words used in ``twin data'', the ``twin study'' item given by Wikipedia might help you.

    So far, I've had more clear idea about the difference between the probability and the likelihood estimation, which can be summarized as:
    • Probability
      • Knowing parameters: Prediction of outcome
    • Likelihood
      • Observation of data: Estimation of parameters
    There still are some concepts I have not quite known yet, such as the ideas presented in the section of ``Likelihood ratio test.''

    Wednesday, December 15, 2010

    [SW] Installation of the LaTeX formula extension in Inkscape 4.07

    First, the ``Effects'' item has been renamed as ``Extensions'' in Inkscape 4.07.

    Then what you need are:

    To install the textext package, just copy the textext.py and textext.inx files to the folder:
    ~/.config/inkscape/extensions/

    Finally, restart your Inkscape and try it. Note the LaTeX formula might appear in some place beyond your working window, so make sure to zoom out your working area and look around for your formula.

    Monday, December 13, 2010

    [QnA] eth0 disappeared...

    I have no idea why this could happened, yet. My Toshiba laptop lost its eth0 again, and this time I was very sure that the driver had been installed properly.

    Again, I found the following posts which solved my problem:
    http://ubuntuforums.org/showthread.php?t=1459907

    Just edit ``/etc/NetworkManager/nm-system-settings.conf'' and let ``managed=true'':

    Thursday, November 04, 2010

    Floating calculation in bash (with formatted output)

    What I wanted was to get a list of incremental floating numbers, like:
    0.0 0.2 0.4 0.6 ... 2.0

    It is possible to accomplish this mission in bash, with the help of bc. My own script is listed below:
    #!/bin/bash
    for i in {0..20..2}
    do
    #f=$(printf %3.1f `echo "scale=1; $i/10" | bc`) # old version
    printf -v f %3.1f `echo "scale=1; $i/10" | bc` # new version
    echo $f
    done

    The bc command was used because bash cannot handle floating calculation directly.

    Sunday, October 24, 2010

    [QnA] Activate the ethernet card of Toshiba L600 laptop (for Ubuntu 10.04)

    I've bought a laptop (Toshiba Satellite L600) several days ago. Everything seems alright when I inserted the Live CD of Ubuntu 10.04 to play example audio and video files. So I installed Ubuntu 10.04 in my new laptop. After the installation, I tried to connect to the Internet for system upgrade and found the pppoeconf complained with ``no Ethernet card'' messages.

    From the searched results and based on my own incomplete test, here are the steps to activate the Ethernet card of the Toshiba Satellite L600:

    Step 1: Check the type of card.
    $ lspci | grep Ethernet
    04:00.0 Ethernet controller: Atheros Communications AR8152 v1.1 Fast Ethernet (rev c1)


    Step 2: Use the keyword of the card to search the driver. What I found is AR81Family-linux-v1.0.1.13.tar.gz

    Step 3: Untar the downloaded files and install the driver.
    $ make
    $ sudo make install
    $ cd src/
    $ sudo cp atl1e.ko /lib/modules/2.6.32-21-generic/kernel/drivers/net/atlx/
    $ sudo depmod -a

    Step 4: Reboot the system then go for pppoeconf to set up the DSL connection.

    Thursday, October 14, 2010

    [Py] Assign values of one list to another

    It is easy to ``copy'' lists in Python, but it is also easy to get things wrong, especially when you ignore something important like what I did.

    Consider the following situation:
    >>> A = [1,2,3]
    >>> B = A
    >>> B[0]=-1
    >>> A
    [-1, 2, 3]

    What I want is to create a new list B which contains identical elements of the original list A. This doesn't work, however. As you can see in the above test, any modifications made on list B will affect list A. The reason is that when we type ``B=A'', the list B is just another name of list A. They are identical and of course are pointed to the same address. See the following tests:

    >>> B is A
    True
    >>> B.index, A.index
    (, )

    So, if we need an independent list B which has a set of values' copy in list A, use ``list slicing'':
    >>> B = A[:]
    >>> B is A
    False
    >>> B.index, A.index
    (, )
    ---
    Ref: An Introduction to Python Lists

    [Py] Be careful when create multi-dimensional lists

    I wrote a note about the creation of multi-dimensional lists in Python, when I had not yet encountered another problem which have emerged recently. The problem is about appending items to the multi-dimensional lists.

    Consider the following example:

    >>> A = [[]]*3
    >>> A
    [[], [], []]
    >>> for i in range(3):
    ...    for j in range(3):
    ...        A[i].append(i+j)
    ...
    >>> A
    [[0, 1, 2, 1, 2, 3, 2, 3, 4], [0, 1, 2, 1, 2, 3, 2, 3, 4], [0, 1, 2, 1, 2, 3, 2, 3, 4]]

    But what I really want is something like
    A = [[0, 1, 2], [1, 2, 3], [2, 3, 4]]

    My guess is that the creation approach doesn't create a list which contains three independent rows, but just create three rows which actually point to the same address or something like that.

    The solution (perhaps not the best one) is to create the rows in the form of list comprehension:

    >>> A = [[] for rows in range(3)]
    >>> A
    [[], [], []]
    >>> for i in range(3):
    ...    for j in range(3):
    ...        A[i].append(i+j)
    ...
    >>> A
    [[0, 1, 2], [1, 2, 3], [2, 3, 4]]

    Friday, October 01, 2010

    [QnA] Change the permission of viminfo to enable the command histroy of Vim

    After upgrading from Ubuntu 8.04 to 10.04, I found the command history of Vim was missing. The reason is simple: in Ubuntu 10.04, the ~/.viminfo file has a 600 permission so only the root can access it.

    To get the command history of vim back, you may change the permission from 600 to 666. I don't know whether this change has any side effects, however. At least for only one user using one computer, this is a quick trick. :-)

    ---
    Ref:

    Thursday, September 30, 2010

    [QnA] Problems when using fbi/fbgs in virtual consoles of Ubuntu 10.04 (Lucid Lynx)

    I upgraded all my computers (2 PCs and 1 laptop) from Ubuntu 8.04 to 10.04 these days. Most things are fine (and even great!), but there is one thing, the GRUB 2,t has brought me some troubles. I could not use fbi and fbgs in the consoles. Of course I ran into Google several times but got no lucks, until yesterday when I found the following thread and links:


    The second link gives a complete guide.

    FYI: To check the resolution given by framebuffer of your computer, use ``sudo hwinfo --framebuffer'' command in the console.

    Sunday, September 19, 2010

    [SW] Use GIMP to save layers of animated GIF

    It is easy to use GIMP to create animation in GIF format (just use Google and you can find many examples). However, to extract individual layers of an animated GIF is another story, and I can't find a straightforward approach in GIMP.

    Fortunately, the solution has been exist. There is a script by

    Monday, September 06, 2010

    [Py] Rubik's cube game

    Although I am not good at solving Rubik's Cube, I am a fan of it. Of course, I am always wondering whether there are programs which can show a 3D Rubik's Cube in my computer so that I can play the cube interactively. And the answer is YES!

    On Pygame site, there is a wonderful program called Rubik's Cube Game meets all my needs. Actually, I've downloaded and tested it several months ago, but until today I finally get clear steps to make the program run properly. My modifications are as follows.
    1. rename Images/*.PNG to Images/*.png
    2. apt-get install python-opengl
    3. download gameobjects and install it
    4. remove *.pyc
    5. rename *.pyw to *.py
    6. run ``python Rubik's Cube.py''

    Thursday, September 02, 2010

    Converting filenames from UPPERCASE to lowercase

    I searched and found the following thread:
    http://blog.mc-thias.org/?title=rename-files-from-upper-case-filename-to&more=1&c=1&tb=1&pb=1

    Based on the post given by Jadu Saikia, I got the bash script of my own version as follows:
    ls * | sed -e p -e 's/.*/\L&/g' |xargs -n 2 mv

    One new thing I've learned in this example is the ``\L'' part, which can be found in sed's FAQ.

    Wednesday, August 04, 2010

    [Py] Install pygame-1.9.1 in Ubuntu (with running a game: Cave Copter)

    I went to pygame's website to see whether there are some very simple examples for me to begin with. After several trials, I found the pygame version of Ubuntu 8.04 was 1.7 and it was too old to run some games, so I decided to install pygame from the source.

    Things were almost easy. Just download and extract the source files and run the setup.py. Some error messages showed up:
    sh: sdl-config: not found
    sh: smpeg-config: not found


    It means you need to install the following libraries.
    $ sudo apt-get install libsdl-dev libsmpeg-dev

    Ran the setup.py again and I got other warning messages as follows.
    FONT : not found
    IMAGE : not found
    MIXER : not found
    PNG : not found
    JPEG : not found
    PORTMIDI: not found
    PORTTIME: not found

    What I installed were:
    libjpeg-dev libpng12-dev libportmidi-dev libsdl-ttf2.0-dev libsdl-image1.2-dev libsdl-mixer1.2-dev

    Finally, ran
    $ sudo python setup.py
    and got new version pygame work!

    ---
    After installing pygame-1.9.1, I tried to test the game, Cave Copter.

    Cave Copter is a game using pygame. To make it run properly in Ubuntu, there still some minor works to do.

    First, we need to change all the double backslashes in the original CaveCopter.py to single slash. Second, we have to change the *.PNG to *.png so that these png files can be recognized.

    Hope I will have time to play with and to learn something from the source code...