Skip to content


Installing OpenCV 2.4.9 in Ubuntu 14.04 LTS

The latest Long Term Support version of Ubuntu(14.04 LTS) is out and a new version of OpenCV was recently released as well. This means that now is a great opportunity to update my OpenCV installation guide to the latest versions, Ubuntu 14.04 LTS and OpenCV 2.4.9.

viz

One of the great additions in this new release of OpenCV is the new viz module, which offers a nice 3D visualizer. This module is based on the great Visualization Toolkit library (VTK) and nicely prepares the users for the upcoming OpenCV 3.

In this guide, I will show you how to install OpenCV with a lot of the features it provides. Here are some of the things that are going to be enabled when you are finished following through with this installation tutorial:

  • viz module (3D visualization)
  • Qt version of the HighGUI module (Better 2D window interface with zoom, image saving capabilities, etc)
  • OpenGL support
  • C++ interface and examples
  • C interface and examples
  • Python interface and examples
  • Java interface and examples
  • Intel Threading Building Blocks (TBB)

Note: I have noticed some copies of my posts elsewhere, so make sure that you are reading this from the original source, at samontab dot com, accessible from here so that you don’t miss the comments.

OK, so the first step is to make sure that everything in the system is updated and upgraded. Open the terminal and write this:

sudo apt-get update
sudo apt-get upgrade

Now, you need to install many dependencies, such as support for reading and writing image files, drawing on the screen, some needed tools, other libraries, etc… This step is very easy, you only need to write the following command in the Terminal:

sudo apt-get install build-essential libgtk2.0-dev libjpeg-dev libtiff4-dev libjasper-dev libopenexr-dev cmake python-dev python-numpy python-tk libtbb-dev libeigen3-dev yasm libfaac-dev libopencore-amrnb-dev libopencore-amrwb-dev libtheora-dev libvorbis-dev libxvidcore-dev libx264-dev libqt4-dev libqt4-opengl-dev sphinx-common texlive-latex-extra libv4l-dev libdc1394-22-dev libavcodec-dev libavformat-dev libswscale-dev default-jdk ant libvtk5-qt4-dev

Time to get the OpenCV 2.4.9 source code:

cd ~
wget http://sourceforge.net/projects/opencvlibrary/files/opencv-unix/2.4.9/opencv-2.4.9.zip
unzip opencv-2.4.9.zip
cd opencv-2.4.9

Now we have to generate the Makefile by using cmake. In here we can define which parts of OpenCV we want to compile. Since we want to use the viz module, Python, Java, TBB, OpenGL, Qt, work with videos, etc, here is where we need to set that. Just execute the following line at the terminal to create the appropriate Makefile. Note that there are two dots at the end of the line, it is an argument for the cmake program and it means the parent directory (because we are inside the build directory, and we want to refer to the OpenCV directory, which is its parent).

mkdir build
cd build
cmake -D WITH_TBB=ON -D BUILD_NEW_PYTHON_SUPPORT=ON -D WITH_V4L=ON -D INSTALL_C_EXAMPLES=ON -D INSTALL_PYTHON_EXAMPLES=ON -D BUILD_EXAMPLES=ON -D WITH_QT=ON -D WITH_OPENGL=ON -D WITH_VTK=ON ..

OpenCVConfig

Check that the above command produces no error and that in particular it reports FFMPEG as YES. If this is not the case you will not be able to read or write videos. Check that Java, Python, TBB, OpenGL, V4L, OpenGL and Qt are all detected correctly.

OpenCVmodulesToBeBuilt

Make sure you scroll up and check that the modules that are going to be built are these:
core flann imgproc highgui features2d calib3d ml video legacy objdetect photo gpu ocl nonfree contrib java python stitching superres ts videostab viz.

If anything is wrong, go back, correct the errors by maybe installing extra packages and then run cmake again.

Now, you are ready to compile and install OpenCV 2.4.9:

make
sudo make install

Now you have to configure OpenCV. First, open the opencv.conf file with the following code:

sudo gedit /etc/ld.so.conf.d/opencv.conf

Add the following line at the end of the file(it may be an empty file, that is ok) and then save it:

/usr/local/lib

Run the following code to configure the library:

sudo ldconfig

Now you have to open another file:

sudo gedit /etc/bash.bashrc

Add these two lines at the end of the file and save it:

PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig
export PKG_CONFIG_PATH

Finally, close the console and open a new one, restart the computer or logout and then login again. OpenCV will not work correctly until you do this.

Now you have OpenCV 2.4.9 installed in your computer with 3D visualization, Python, Java, TBB, OpenGL, video, and Qt support.

Check out the cool Qt interface which provides image viewing capabilities with zoom, as well as the ability to save the current image with just one click.

If you zoom in enough, you can see the RGB (or intensity) values for each pixel.

Now let’s build some samples included in OpenCV:

cd ~/opencv-2.4.9/samples/c
chmod +x build_all.sh
./build_all.sh
These examples use the old C interface:
./facedetect --cascade="/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml" --scale=1.5 lena.jpg

./facedetect --cascade="/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml" --nested-cascade="/usr/local/share/OpenCV/haarcascades/haarcascade_eye.xml" --scale=1.5 lena.jpg

The following examples use the new C++ interface:

~/opencv-2.4.9/build/bin/cpp-example-grabcut ~/opencv-2.4.9/samples/cpp/lena.jpg

~/opencv-2.4.9/build/bin/cpp-example-calibration_artificial

Now let’s run some Python code:

python ~/opencv-2.4.9/samples/python2/turing.py

Now you can build a Java sample using ant for example. (Make sure that you change /home/samontab/ with your actual home directory):

cd ~/opencv-2.4.9/samples/java/ant
ant -DocvJarDir=/home/samontab/opencv-2.4.9/build/bin -DocvLibDir=/home/samontab/opencv-2.4.9/build/lib

java_ant

Now let’s read a video and use OpenGL with Qt through this great sample that detects the features from the video, then estimates the 3D location of the structure using POSIT, and finally uses OpenGL to draw in 3D (great sample Javier):

cd ~/opencv-2.4.9/samples/cpp/Qt_sample
mkdir build
cd build
cmake ..
make
./OpenGL_Qt_Binding

posit

And finally, let’s build a sample using the 3D visualization module viz:

cd ~/opencv-2.4.9/samples/cpp/tutorial_code/viz
g++ -o widget_pose `pkg-config opencv --cflags` widget_pose.cpp `pkg-config opencv --libs`
./widget_pose

viz

As you can see, now you can use OpenCV with C++, C, Python, and Java. The Qt enhanced 2D interface is enabled, 3D data can be displayed using OpenGL directly, or using the new viz module. Multi threading functionality is enabled using TBB. Also, video support is enabled as well.

If you correctly finished this tutorial, you are now ready to do some nice computer vision work.

Posted in Image Processing, Open Source, Programming, Qt.


My New OpenCV Computer Vision Application Programming Video Course

OpenCV_Computer_Vision_Application_ProgrammingAfter writing articles helping people to install OpenCV here on this blog, some asked me to share a little more about OpenCV, not just the installation part. I started thinking about a way to deliver this information when suddenly Packt publishing contacted me about making a video course tutorial for OpenCV. I knew it was the perfect solution, so I immediately said yes. After the publication of the video course at Packt, I was glad to see it appear also in the official website of OpenCV.

This video course starts right at the beginning, with an explanation of what OpenCV is and its installation. Then, you learn all the basics of OpenCV, followed by some of the basics of image processing. Then, you will be ready to detect objects, recognize faces, train your own detector, remove distortion from your photos, and play with images in 3D.

Here are the things that you will learn with this video course:

  • Learn what OpenCV is and how to install it on Linux and Windows
  • Development with OpenCV using the recommended C++ interface, as well as an introduction to the Python and C interfaces.
  • Segment objects in your images using grabcut and watershed, cluster your data, and spot interesting points in the image
  • Merge different images into a single panorama using the technique called panorama stitching
  • Detect common objects in your images, like faces, eyes, or people
  • Train your own object detector to detect custom objects
  • Recognize a face among many others
  • Learn to calibrate your camera
  • Remove or reduce the distortion of an image caused by the lens, commonly known as barrel distortion
  • Change the perspective of an image to match a different 3D pose
  • Create an image that represents depth information of the scene using stereoscopic images

This is an easy to follow video course for people that are just starting with OpenCV. Even people that are used to OpenCV may benefit from some of the more advanced videos since you can just pick and choose which video you want to learn from.

You can check out the video course here.

Posted in Image Processing, Open Source, Programming.


How to make HD screencasts using free tools

A screencast is basically a video of your computer screen with your voice as the audio. A screencast is very useful for tutorials or teaching how to use something with your computer.
There are a couple of paid programs that allow you to create screencasts, but in this post I will show you how to make them using only free tools(although you need to be running Windows for this tutorial, which is not free, sorry about that).

The first step is to download and install the codec that will allow us to compress the video. We are going to use one of the best standards for HD video: H.264/MPEG-4 AVC. The specific implementation to install here is x264vfw.

You need to install the 32 bits version (even if you have a 64 bits system). After you install the 32 bits version, try to install the 64 bits version as well (you may not be able to do it in a 32 bit system).

Now, install the latest version of camstudio. It is a great program that will allow you to record your voice and your desktop. Make sure that you also install the Lossless Video Codec as well.

OK, now you should have camstudio and its Lossless Video Codec installed. Make sure that you have your mic and/or video camera connected to your computer. Now we are going to configure camstudio to make it screencast ready.

Start camstudio and set the following options:

  • Options-> Record audio from microphone
  • Options-> Program Options -> Play AVI file when recording stops -> Do not play AVI file
  • Options-> Program Options -> Name of AVI file -> Automatic file naming (use date and time)
  • Options-> Program Options -> Minimize program on start recording (not checked)
  • Options-> Program Options -> Directory for recording -> Use user specified directory… (and specify a directory where you want your videos to be saved)

Now, go to Options-> Video options, and select the following:
camstudio_lossless

  • Compressor: CamStudio Lossless Codec 1.5 (or newer)
  • Quality 100
  • Select Auto Adjust
  • Move the slider to where you have a Playback rate of 25 frames / second (the default one is 200 fps!)

Now go to Options-> Audio options-> Audio options for microphone, and select the following:
camstudio_audio

  • Audio Capture Device: Select your device
  • Recording Format, select 44.1kHz, stereo, 16 bit.
  • Compressed format: PCM

Now we are going to set which area of the screen to record. Go to Region->Fixed Region and set these values:
camstudio_fixedregion

  • Left: 80
  • Top: 25
  • Width: 1280
  • Height: 720

The most important thing to note here is the width and height of 1280 and 720 respectively. This is widescreen HD format (720p) and it is very important that you use these values. If you use other, non standard values, you will end up with problems in your video. If you have a larger screen, you may want to use a width of 1920 and a height of 1080, which is even better (1080p). The other values, left and top, should be set depending on the actual area that you want to record of your desktop. Remember that left plus width and top plus height should be less or equal to your total screen width and height respectively.

Alternatively to selecting a specific region in your screen, you can first adjust your screen resolution to 1280×720 (or 1920×1080), and select Region-> Full Screen instead. I prefer using a region because you can show your software in your native resolution, and also you have the option to not show the clock, and the menu bar, etc. This is specially important for continuity when editing videos later.

OK, now go ahead and make a couple of quick tests. Click on the record button(red circle), start talking, moving your mouse, opening folders, etc. After some seconds, press stop(blue square). After a moment, a video should be waiting for you in the location you specified earlier without you having to do anything else. Go there and check it. Make sure that the video came out OK, that you can see the areas that you want, that your voice is loud and clear, that the video resolution and frame rate are what you expected, and that you are comfortable with this recording procedure. Also, always make sure that you have at least a couple of seconds at the beginning and at the end of your recordings. Specially at the end, because the encoding technique that we will use cuts one or two seconds at the end, depending on the length of your video.

Before you start doing real screencasts, let’s check a couple of issues. Camstudio is a great program, but sometimes it crashes, and it forgets all your settings, which is unfortunate (incredibly annoying and frustrating). That’s why it is good to save your preferences, which are stored in four files located at the installation directory (C:\Program Files (x86)\CamStudio 2.6b). Once you have set all your preferences, just copy these four files: Camdata.ini, CamLayout.ini, CamShapes.ini, CamStudio.ini into a safe place (C:\Users\Public\Documents\camstudioconfig for example). If camstudio crashes and forgets your preferences, simply close the software, copy your files back and continue normally.

After you record a couple of videos, you can edit them. We are going to use a video editor called virtualdub. Download and open it. Drag and drop a video there. You can now see all the frames that compose the video. You can select some frames and delete them for example. Also, you can append another video. You can also do many other things, but appending videos and removing frames is all you need to create a nice screencast. It is important that all your videos are recorded with the same settings, like width, height, even sound should be the same.

Before you edit a video, always check these settings in virtualdub:

  • Make sure that Video->Full processing mode is selected
  • Make sure that Audio->Direct stream copy is selected

Now, go to Video-> compression and select x264vfw:
virtualdub_compression

Click on configure and set the following options:
virtualdub_configuration

  • enable zero latency
  • enable virtualdub hack

Click OK, OK
Now you can edit the screencast by appending your videos, and removing frames. You can take a look at what virtualdub has to offer here.
Once you are finished editing your screencast, you can go to File->save as avi. It will generate the first version of your screencast, but we need to compress it even further and change it into a different format.

Now comes the final step. Install and open vlc and select Media->Convert/Save. Under file selection, click Add and select the AVI file you just created with virtualdub. Click on Convert/Save. On Destination folder, copy the same file path as the source, but end the filename with mp4 instead of avi. Under profile, make sure that Video H.264 + AAC (MP4) is selected. Click on start, and after some minutes, you will have your HD screencast ready in the same folder that you selected at the beginning.

Note:
If you need to make a screencast of Linux, or other operating system, you can use virtualbox. Just use it as a normal windows application, and everything will be recorded. Make sure that your region is set so that it covers the area that you want to record. If you are interested in a native application, you can take a look at recordmydesktop.

Note 2:
If you already have a recording in camstudio and want to change the frame rate, you can do that easily with virtualdub. Open the video in virtualdub, go to video, select direct stream copy. Go to video, select frame rate.
Under frame rate conversion, select convert to fps, and put 25 (or the desired value). Go to file, select save as avi. It should process the file quickly.

Posted in General, Open Source.


Technical reviewer of a book about computer vision projects solved using OpenCV

There is a new book about OpenCV:

Mastering OpenCV with Practical Computer Vision Projects.

7829OS_Mastering OpenCV with Practical Computer Vision Projects.jpgI was honored to be invited to participate as a technical reviewer of the book, and it was really fun to read. Each chapter shows a specific real world problem and teaches you how it can be solved using OpenCV. This is the work of seven authors, and the projects are great. I really recommend this book if you are already using OpenCV, because it deals with more advanced details, and in some cases it shows you how to use other libraries to fill in where OpenCV lacks for specific purposes.

Some of the cool things that this book covers are how to make OpenCV powered apps for Android and iOS, interfacing OpenCV with the Kinect, number plate detection, optical character recognition (OCR), augmented reality, structure from motion, face detection and tracking.

If you are interested in using OpenCV in real world scenarios, this book will definitely help you. Although you will need to know the basics of image processing or computer vision and programming first as this book is mostly focused on the actual practical projects.

Posted in Image Processing, Open Source, Programming.


Playing with astrophotography

One of the easiest subjects to photograph in the night sky is the Moon. Everyone knows where it is, and it looks large and bright from the earth(well, unless it is in the new moon phase).
moon

Yesterday, Jupiter was passing close to the Moon, as seen from the Earth.
jupiter_close_to_the_moon

I tried to get a close up of Jupiter and the Moon in the same frame, but the brightness of the Moon was overexposing the photograph.
jupiter_moon_too_bright

When I properly exposed the Moon, Jupiter was not very visible.
jupiter_moon_too_dark

I could have used HDR techniques here to merge differently exposed photos into a single one that had Jupiter and the Moon properly exposed, but I changed my mind and started focusing on Jupiter alone.

Removing the Moon from the frame allowed me to gather more light from Jupiter and its surroundings, and that’s when four other objects appeared in my picture.
jupiter_four_moons

Checking with Stellarium, I confirmed that these objects were Europa, Io, Ganymede, and Callisto. They are the four largest moons of Jupiter!.

I never thought that I would be able to photograph the moons of Jupiter from the Earth using my own camera, but there they are!.
moons_of_jupiter

Here is the previous photo aligned with the simulated sky from Stellarium. Cool!
jupiter_moons_aligned

Posted in General, Photography.


Using OpenCV in Sage

OpenCV is an awesome free open source library for computer vision, image processing, and even some machine learning.
Sage is an awesome free open source mathematical software system that integrates many other libraries and software into a single, easy to use interface for all your math needs.

I really like both projects, and have been using them separately, but in this post I will show you how you can use OpenCV in the Sage environment. This means that you will be able to use all the power of the Sage Notebook Server, NumPy, SciPy, Matplotlib, PIL (Python Imaging Library), R, and almost a hundred other open source packages for all your image processing needs.

sage0

The first step is to install the latest version of OpenCV in your system with the new Python bindings. You must have the Python bindings working correctly for this to work. The easiest way of doing this is to follow my own tutorial for installing OpenCV. You can easily change the version for installing the latest OpenCV version that is out there, the tutorial should still work. I used it to install OpenCV 2.4.3 in Ubuntu 12.10, and it worked perfectly.

To make sure that OpenCV is installed correctly, go to the console and start Python by running this command:

python

You should see the python console waiting for you. There, write the following:

import cv2

Importing OpenCV cv2 module into python
If no error appeared, everything is great, you can continue. If there are some errors, you need to fix them first. You can exit with Control-D, or by typing exit().

By the way, currently there are two OpenCV Python modules, cv and cv2. The legacy C version API of OpenCV can be accessed via cv, and the new C++ interface of OpenCV is available via cv2. Therefore, you are encouraged to use cv2 because that’s where the good stuff is.

Now that we have OpenCV with Python correctly installed, we need to install Sage.
First, check if you are running a 32 or 64 bit system by using this command:

uname -m

You will see x86_64, which means 64 bits or something like i686 or i386, which means 32 bits.

Now we need to download Sage from here. You can pick where to download from, as well as if you want the 32 or 64 bits version. I usually download it from the University of Washington which is where the lead developer of Sage, William Stein, teaches math but you can choose any other location that you like. You are looking for a file that has a name similar to this one: sage-5.4.1-linux-32bit-ubuntu_12.04.1_lts-i686-Linux.tar.lzma. For the next steps, I will be using that file. Remember that you may need to change the file or folder names for your specific situation.

After you download the file, you will need to extract it. On the console, change your directory to where you downloaded the file and extract it:

cd ~/Downloads
tar --lzma -xf sage-*

Now you will have to wait for a few minutes for it to decompress a lot of files. Notice how I did not use the verbose option for extracting (I used -xf instead of -xvf). This is because it takes a lot longer to decompress when it has to output every file name. Since nothing is being printed on the screen, it is faster but you may think that nothing is happening. Don’t worry, everything is fine. Just leave it alone until it finishes decompressing.

Now we are going to configure it so that we can call it from anywhere.

mv sage-5.4.1-linux-32bit-ubuntu_12.04.1_lts-i686-Linux sage-5.4.1
sudo mv sage-5.4.1 /opt/
sudo cp /opt/sage-5.4.1/sage /usr/local/bin/
sudo gedit /usr/local/bin/sage
  1. Copy the line that says #SAGE_ROOT=/path/to/sage-version.
  2. Remove the comment character (#) in the line you just copied.
  3. Change the path to /opt/sage-5.4.1 (or the version you are installing).
  4. Save the file and close the editor.

sage_root

And now you can start Sage by using this command anywhere:

sage

You will have to wait for a few moments this first time you run it. You should then see the command prompt of Sage waiting for your input. Exit for now by running this command:

exit

If everything is fine, you can now delete the downloaded file to save some space:

rm ~/Downloads/sage-5.4.1-linux-32bit-ubuntu_12.04.1_lts-i686-Linux.tar.lzma

OK, so now we also have Sage correctly installed in the system.

Let’s install OpenCV into Sage:

cd /usr/local/lib/python2.7/dist-packages/
cp cv2.so /opt/sage-5.4.1/local/lib/python2.7/site-packages/
cp cv.py /opt/sage-5.4.1/local/lib/python2.7/site-packages/
cd ~

To make sure that OpenCV is correctly installed in Sage, go to the console and start Sage by running this command:

sage

You should see the Sage console waiting for you. There, write the following:

import cv2

If no error appeared, everything is great, you can continue. If there are some errors, you need to fix them first. At this point, it should report the following error:

RuntimeError: module compiled against API version 6 but this version of numpy is 4.

This happens because Sage(as of v5.4.1) still comes with an older version of NumPy(v1.5.1). You can tell which is the included version of NumPy by doing this in Sage:

import numpy
numpy.version.version
exit

So, if you have a newer version of Sage (this fix is scheduled for v5.6), and did not get the error, you can skip the next step.

Let’s update Sage’s NumPy to v1.7.0b2 so that we can use OpenCV with it:

cd ~
wget https://spkg-upload.googlecode.com/files/numpy-1.7.0b2.spkg
sage -f numpy-1.7.0b2.spkg

Now you should be able to run OpenCV functions in Sage.

Let’s use the Sage Notebook interface with OpenCV.
Start sage, run notebook(), and follow the instructions for using the notebook interface. For more advanced options for the notebook server, you can check here.

Once you have a new worksheet open, define some functions to convert arrays between NumPy, OpenCV and PIL:

import cv2, numpy, Image, ImageDraw

def cv2np(image):    
    rgbimage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    return rgbimage/255.
    
def pil2np(image):
    rgbimage = numpy.array(image)
    return rgbimage/255.
    
def cv2pil(image):
    rgbimage = cv2.cvtColor(lenna, cv2.COLOR_BGR2RGB)
    pilimage = Image.fromarray(rgbimage)
    return pilimage

Now, in another cell let’s load an image and find a face using the trained frontal face model. (Make sure that you change the path to your image):

image_path = "/home/username/OpenCV-2.4.3/samples/c/lena.jpg"
lenna = cv2.imread(image_path, cv2.CV_LOAD_IMAGE_COLOR)
cascade_fn = "/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml"
cascade = cv2.CascadeClassifier(cascade_fn)
gray = cv2.cvtColor(lenna, cv2.COLOR_BGR2GRAY)
rects = cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=4, minSize=(30,30))
for x1, y1, width, height in rects:    
    faces_rectangle = [x1, y1, x1 + width, y1 + height]
faces_rectangle

If you use lena.jpg, you should see the following result:

[217, 203, 386, 372]

Which is the location of the bounding box of the detected face of Lenna.
Now, let’s use PIL to draw the detection:

lenna_pil = cv2pil(lenna)
draw = ImageDraw.Draw(lenna_pil)
draw.ellipse((x1, y1, x1+width, y1+height), outline="green")
draw.ellipse((x1+1, y1+1, x1+width-1, y1+height-1), outline="green")
draw.ellipse((x1+2, y1+2, x1+width-2, y1+height-2), outline="green")

To be able of changing the thickness of the ellipse in PIL, you need to install the aggdraw module, so I just drew three ellipses instead.

Finally, it is time to show the detection:

matrix_plot(pil2np(lenna_pil)).show( axes=True, frame=True, figsize=8, aspect_ratio=1)

sage_opencv
And that’s it. This is just a simple example of object detection in OpenCV using the Sage environment. Feel free to explore Sage and OpenCV now that you can use them in the same interface.

Posted in Image Processing, Open Source.


Installing OpenCV in the Nokia N900 (maemo)

In this post, I will describe the entire procedure needed to install OpenCV and compile your computer vision applications in the Nokia N900 from scratch. This means that you can make advanced computer vision processing on the go.

First of all make sure that you back up all your N900 data. No kidding. We are going to make some changes that could possibly brick your phone. This means that you may need to re flash your firmware if anything goes wrong. If you are not OK with this, stop reading. I will not be held responsible for any problems you may encounter. You have been warned.

The N900 is an awesome device, it is a Linux computer in the form of a smartphone. Because of that, you can do pretty much anything you could do on a regular Linux computer and more, since you have all the extra features of a smartphone like sensors and a battery. One of the things a regular Linux computer can do is to use an advanced computer vision library (OpenCV), which is the library we are going to install on the N900.

The first step is to configure the repositories. A repository is a place where programs are stored. You can have different repositories available on your system. Each repository that you have enabled in your system allows you to install different sets of programs. Note that on the N900, repositories are called catalogs.

To manage your repositories on your N900, go to the App. Manager and click on the menu on top (where it says Application manager). There, select Application Catalogs.

Here (maybe after waiting a little) you will see the current list of enabled and disabled catalogs. Disabled catalogs are not considered by the system, so all the applications you can install come from the enabled catalogs. Write down which catalogs are enabled and which ones are disabled as this is your original configuration and you may want to go back to it after we are finished.

Now, let’s add some catalogs. Click on the New button and fill in the information provided for the three following catalogs:

Maemo SDK: This catalog provides core system utilities that we will need to build programs.

Catalog Name: Maemo SDK
Web address: http://repository.maemo.org/
Distribution: fremantle/sdk
Components: free non-free
Disabled: Unchecked

Maemo tools: This catalog provides tools that are very useful, like nano or wget.

Catalog Name: Maemo tools
Web address: http://repository.maemo.org/
Distribution: fremantle/tools
Components: free non-free
Disabled: Unchecked

Maemo extras-testing: This catalog provides more applications than the ones in the default Maemo catalog (extras), although they are not as thoroughly tested.

Catalog Name: Maemo extras-testing
Web address: http://repository.maemo.org/extras-testing/
Distribution: fremantle
Components: free non-free
Disabled: Unchecked

These catalogs provide different applications that we will need later. Enable all of them.

Now exit the Application Catalogs screen. The N900 will automatically update the list of applications after you changed the repositories. If you didn’t see any update, click on the Update button just to be sure. Now click on Download->All to see the list of applications available to install. You should install the following apps:

openssh client and server
rootsh
sudser
Personal IP Address

When you install OpenSSH, you will be asked for a password. This is the root password, so keep it safe.

Now close the application manager and open the console (X Terminal). In there, you will setup a password for the default user, which is user. Write this:

sudo passwd user

And write a password for the user user, which is the default user (non root privileges). Close the console or write exit to exit.

OK, on the N900 desktop you now should be able to see your current IP address. You can use that IP to connect via SSH or FTP to your N900 with either root or user using the passwords you just set for them. If you don’t have Linux installed on your computer, you can use Filezilla for FTP and PuTTy for SSH. Make sure that you can connect to your N900 with the user account.

Now we will be working with the command line only, so I suggest you to connect from your computer via SSH (as user) for easier writing (or copy pasting). Make sure that the App. Manager is closed before continuing.

On the console, write the following:

sudo apt-get install build-essential wget grep-gnu libglibmm-2.4-dev nano libpng12-dev libjpeg62-dev libtiff4-dev libgtk2.0-dev unzip

It should install all these packages without a problem. If it asks “Install these packages without verification?” Answer yes.

OK, your N900 is ready to compile software. We are now going to get and install OpenCV by writing the following:

sudo apt-get install libcv4 libhighgui4 libcvaux4 opencv-doc libcv-dev libhighgui-dev libcvaux-dev

Once it is finished installing the packages, go to the App. Manager and disable all of the three repositories we used (Maemo SDK, Maemo Tools, Maemo extras-testing).

Now let’s check that everything is correctly installed. Run this command:

pkg-config --libs --cflags opencv

You should see something similar to:

-I/usr/include/opencv  -lcv -lhighgui -lcvaux -lml -lcxcore

Now you have OpenCV correctly installed in your N900. Great!, now what?.

Let’s compile something. First, download this example that I prepared:

wget http://www.samontab.com/web/files/opencv-n900-test.zip
unzip opencv-n900-test.zip

Compile the project with this line:

g++ -o test main.c `pkg-config --libs --cflags opencv`

And now you can run it with this command:

./test lena.jpg

It will read an image (lena.jpg by default if none is given in the command line), invert the value of the pixels, and save the processed image as processedImage.png.

You should see something like this:

And that’s it. Now you can use OpenCV in your Nokia N900!

Posted in Image Processing, Open Source, Programming.


How I went from obese to normal weight by changing my behavior to lose 20kg (44 pounds)

I was fat, and I was getting fatter every day. On the day that I found out that I was literally obese, I decided to change my behavior so that I could live with a normal weight.
Being the nerd that I am, I started searching for scientific articles that I could use to lose weight and change my behavior. One of the best and simple suggestions that I found about which type of food I should be eating was the healthy eating plate, and since it comes from a respectable source, I decided to test it. Here is the result after basing my food intake on that advice.

Success!. I got into the normal weight range by losing 20kg (44 pounds), and I continue losing weight. By looking at the graph, you may notice that my weight actually increased around May, September, and November. I was traveling abroad those days. That means that it was harder to weigh myself as well as controlling what I was eating. The result of those two things combined?, weight increase. When I got back home, I could weigh myself every day, and control what I was eating, which instantly made me start decreasing my weight again.

After researching on these topics, applying the concepts and actually getting to my goal, I think that these are some of the most important ideas that I learned:

Keep your goal on focus to motivate yourself

It has been reported that focusing on a specific goal gives you better results compared to focusing on accomplishments or not having a goal at all.
Your goal should be something that you can measure, like losing X kg, or staying inside the normal weight BMI range, etc. It is important that your goal can be measured so that every time you weigh yourself you know how close or far away you are from your goal. Also, it allows you to test how good or bad specific behavior changes are for your goal. For example, you could quit drinking alcohol, eat more vegetables, or do more exercises, and see how they affect your specific goal. That way, you will be more motivated to keep the positive behavior changes, and discard the negative ones because you can actually see how they affect your goal.

Weigh yourself everyday, roughly at the same time

You should not be afraid to look at the numbers the scale is showing to you. Those numbers help you to reach your goal, so make sure that you weigh yourself every day and keep a log of it. You can use pen and paper, or a worksheet, or Google Docs, or anything else that you prefer, but make it as simple as possible because otherwise you will not use it.
Your weight changes constantly through the day, so it is best to always measure it at the same time every day. To keep you motivated, I recommend you to weigh yourself in the mornings because that is when you are the lightest. If you are wondering why, take a look at this cool video by Derek from veritasium.

You can eat whatever you like, as long as it is an exception

You should only feed yourself with healthy food on a daily basis. That’s the key. If you have that lifestyle, you can also eat anything you want on certain special occasions, as long as you keep those occasions as exceptions and not as your main food source. Think about it, it doesn’t really matter if you eat a couple slices of pizza and soda once or twice a month, but if you eat it almost every day, you will get fat. Simple. Just keep your daily food intake healthy, and you can eat anything you want on certain occasions. Some examples of this idea are the “cheat day” from the slow-carb diet of Tim Ferris, as well as the concept behind the BBC documentary Eat, fast, & live longer where they suggest very low calorie intake days followed by days where you can eat whatever you want. Remember to check your weight data log to see how those special days affect your goal, so that you can set their frequency correctly.

Posted in General.


Installing OpenCV 2.4.1 in Ubuntu 12.04 LTS

EDIT: I published a new guide using Ubuntu 14.04 LTS and OpenCV 2.4.9 here.

The latest Long Term Support version of Ubuntu(12.04 LTS) is out and a new version of OpenCV was released as well. This means that now is a great opportunity to update my OpenCV installation guide to the latest versions, Ubuntu 12.04 LTS and OpenCV 2.4.1.

We are going to setup OpenCV to use the new Qt highgui interface, which is much better than the simple highgui interface. Also, we will install OpenCV with support for OpenGL, as well as reading and writing videos, access to a webcam, Python, C and C++ interfaces, and Intel Threading Building Blocks (TBB).

OK, so the first step is to make sure that everything in the system is updated and upgraded:

sudo apt-get update
sudo apt-get upgrade

Now, you need to install many dependencies, such as support for reading and writing image files, drawing on the screen, some needed tools, etc… This step is very easy, you only need to write the following command in the Terminal:

sudo apt-get install build-essential libgtk2.0-dev libjpeg-dev libtiff4-dev libjasper-dev libopenexr-dev cmake python-dev python-numpy python-tk libtbb-dev libeigen2-dev yasm libfaac-dev libopencore-amrnb-dev libopencore-amrwb-dev libtheora-dev libvorbis-dev libxvidcore-dev libx264-dev libqt4-dev libqt4-opengl-dev sphinx-common texlive-latex-extra libv4l-dev libdc1394-22-dev libavcodec-dev libavformat-dev libswscale-dev

Time to get the OpenCV 2.4.1 source code:

cd ~
wget http://downloads.sourceforge.net/project/opencvlibrary/opencv-unix/2.4.1/OpenCV-2.4.1.tar.bz2
tar -xvf OpenCV-2.4.1.tar.bz2
cd OpenCV-2.4.1

Now we have to generate the Makefile by using cmake. In here we can define which parts of OpenCV we want to compile. Since we want to use Python, TBB, OpenGL, Qt, work with videos, etc, here is where we need to set that. Just execute the following line at the terminal to create the appropriate Makefile. Note that there are two dots at the end of the line, it is an argument for the cmake program and it means the parent directory (because we are inside the build directory, and we want to refer to the OpenCV directory, which is its parent).

mkdir build
cd build
cmake -D WITH_TBB=ON -D BUILD_NEW_PYTHON_SUPPORT=ON -D WITH_V4L=ON -D INSTALL_C_EXAMPLES=ON -D INSTALL_PYTHON_EXAMPLES=ON -D BUILD_EXAMPLES=ON -D WITH_QT=ON -D WITH_OPENGL=ON ..

Check that the above command produces no error and that in particular it reports FFMPEG as YES. If this is not the case you will not be able to read or write videos. Also, check that Python, TBB, OpenGL, V4L, OpenGL and Qt are detected.

If anything is wrong, go back, correct the errors by maybe installing extra packages and then run cmake again. You should see something similar to this:

Now, you are ready to compile and install OpenCV 2.4.1:

make
sudo make install

Now you have to configure OpenCV. First, open the opencv.conf file with the following code:

sudo gedit /etc/ld.so.conf.d/opencv.conf

Add the following line at the end of the file(it may be an empty file, that is ok) and then save it:

/usr/local/lib


Run the following code to configure the library:

sudo ldconfig

Now you have to open another file:

sudo gedit /etc/bash.bashrc

Add these two lines at the end of the file and save it:

PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig
export PKG_CONFIG_PATH

Finally, close the console and open a new one, restart the computer or logout and then login again. OpenCV will not work correctly until you do this.

Now you have OpenCV 2.4.1 installed in your computer with Python, TBB, OpenGL, video, and Qt support.

Check out the cool Qt interface which provides image viewing capabilities with zoom, as well as the ability to save the current image with just one click.

If you zoom in enough, you can see the RGB (or intensity) values for each pixel.

Now let’s build some samples included in OpenCV:

cd ~/OpenCV-2.4.1/samples/c
chmod +x build_all.sh
./build_all.sh

Now we are ready to run the examples:

./facedetect --cascade="/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml" --scale=1.5 lena.jpg

./facedetect --cascade="/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml" --nested-cascade="/usr/local/share/OpenCV/haarcascades/haarcascade_eye.xml" --scale=1.5 lena.jpg

~/OpenCV-2.4.1/build/bin/grabcut ~/OpenCV-2.4.1/samples/cpp/lena.jpg

~/OpenCV-2.4.1/build/bin/calibration_artificial

python ~/OpenCV-2.4.1/samples/python2/turing.py

Posted in Image Processing, Open Source, Programming.


MPD on the N900 or how to use your Nokia N900 as a Wireless Home Music System

In a previous post, I showed you how to listen on any device the music you have stored on a Symbian phone. In this post, I will teach you to do the opposite: control the music being played on your N900 with any device. The nice thing about this is that you can connect your N900 to your main speakers. That way, you will be using your Nokia N900 as a wireless home music system that is small, quiet and portable. After finishing this tutorial, you will also be able to connect to your N900 via SSH and FTP, manage your software repositories, compile applications, and setup scripts to be run at boot time.

First of all make sure that you back up all your N900 data. No kidding. We are going to make some changes that could possibly brick your phone. This means that you may need to re flash your firmware if anything goes wrong. If you are not OK with this, stop reading. I will not be held responsible for any problems you may encounter. You have been warned.

The N900 is an awesome device, it is a Linux computer in the form of a smartphone. Because of that, you can do pretty much anything you could do on a regular Linux computer and more, since you have all the extra features of a smartphone like sensors and a battery. One of the things a regular Linux computer can do is to play music with a great program called Music Player Daemon (MPD), which is the program we are going to install on the N900.

The first step is to configure the repositories. A repository is a place where programs are stored. You can have different repositories available on your system. Each repository that you have enabled in your system allows you to install different sets of programs. Note that on the N900, repositories are called catalogs.

To manage your repositories on your N900, go to the App. Manager and click on the menu on top. There, select Application Catalogs.

Here (maybe after waiting a little) you will see the current list of enabled and disabled catalogs. Disabled catalogs are not considered by the system, so all the applications you can install come from the enabled catalogs. Write down which catalogs are enabled and which ones are disabled as this is your original configuration and you may want to go back to it after we are finished.

Now, let’s add some catalogs. Click on the New button and fill in the information provided for the four following catalogs:

Maemo SDK: This catalog provides core system utilities that  we will need to build programs.

Catalog Name: Maemo SDK
Web address: http://repository.maemo.org/
Distribution: fremantle/sdk
Components: free non-free
Disabled: Unchecked

Maemo tools: This catalog provides tools that are very useful, like nano or wget.

Catalog Name: Maemo tools
Web address: http://repository.maemo.org/
Distribution: fremantle/tools
Components: free non-free
Disabled: Unchecked

Maemo extras-testing: This catalog provides more applications than the ones in the default Maemo catalog (extras), although they are not as thoroughly tested.

Catalog Name: Maemo extras-testing
Web address: http://repository.maemo.org/extras-testing/
Distribution: fremantle
Components: free non-free
Disabled: Unchecked

Maemo extras-devel: This catalog contains many useful applications but some of them are in heavy development. This catalog should be disabled by default and enabled only temporarily to install specific applications. Make sure that you disable Maemo extras-devel when you add it.

Catalog Name: Maemo extras-devel
Web address: http://repository.maemo.org/extras-devel/
Distribution: fremantle
Components: free non-free
Disabled: Checked

These catalogs provide different applications that we will need later. Disable Maemo extras-devel and enable the other three.

Now exit the Application Catalogs screen. The N900 will automatically update the list of applications after you changed the repositories. If you didn’t see any update, click on the Update button just to be sure. Now click on Download->All to see the list of applications available to install. You should install the following apps:

openssh client and server
rootsh
sudser
Personal IP Address

When you install OpenSSH, you will be asked for a password. This is the root password, so keep it safe.

Now close the application manager and open the console (X Terminal). In there, you will setup a password for the default user, which is user. Write this:

sudo passwd user

And write a password for the user user, which is the default user (non root privileges). Close the console or write exit to exit.

OK, on the desktop you now should be able to see your current IP address. You can use that IP to connect via SSH or FTP to your N900 with either root or user using the passwords you just set for them. If you don’t have Linux installed on your computer, you can use Filezilla for FTP and PuTTy for SSH. Make sure that you can connect to your N900 with the user account.

Now we will be working with the command line only, so I suggest you to connect from your computer via SSH (as user) for easier writing (or copy pasting). Make sure that the App. Manager is closed before continuing.

On the console, write the following:

sudo apt-get install build-essential wget grep-gnu libglibmm-2.4-dev nano mpc libao0 libaudiofile-dev libaudiofile0 libcurl3-dev libcurl3 libpulse-dev pulseaudio libavcodec-dev

It should install all these packages without a problem. When it is finished, go to the App. Manager, enable Maemo extras-devel and then close the App. Manager. Ignore any updates that are offered by your phone at this point.

Now go back to the console, and write the following (make sure that the App. Manager is closed before you do so):

sudo apt-get install libasound2-dev libmad0-dev libid3tag0-dev libflac-dev libflac++-dev

If  it asks “Install these packages without verification?” Answer yes.

Once it is finished installing the packages, go to the App. Manager and disable all of the four repositories we used (Maemo SDK, Maemo Tools, Maemo extras-testing, Maemo extras-devel).

OK, now your N900 is ready to compile software. We are now going to get and compile Music Player Daemon (MPD).

Open the console (X Terminal) and write the following:

cd
mkdir tempdelme
cd tempdelme
wget http://downloads.sourceforge.net/project/musicpd/mpd/0.16.6/mpd-0.16.6.tar.gz
tar -xvzf mpd-0.16.6.tar.gz
cd mpd-0.16.6/
./configure
make
sudo make install

After some time, it should be ready. Now MPD is installed in /usr/local/bin/mpd. Check that everything is OK with this command (Thanks Martin for suggesting the –no-daemon option):

/usr/local/bin/mpd --version --no-daemon

It should display the formats it is able to play (i.e. mp3, flac, wav, etc). If you need more functionality than what is presented, install the extra needed libraries and then run ./configure; make; sudo make install again. Most people should be OK with the current settings.

Now that we have MPD installed, we need to configure it. Write this:

nano /home/user/.mpdconf

This will open a text editor. Write the following in there:

port                    "6600"
music_directory         "/home/user/MyDocs/music"
playlist_directory      "/home/user/.mpd/playlists"
db_file                 "/home/user/.mpd/mpd.db"
log_file                "/home/user/.mpd/mpd.log"

user "user"

bind_to_address "any"

audio_output {
        type            "alsa"
        name            "MPD ALSA"
        mixer_type      "software"
}

Make sure that all your music files and folders are inside the defined music_directory.

Now let’s create those directories

mkdir -p /home/user/.mpd/playlists
mkdir -p /home/user/MyDocs/music

And now put some music files in the music_directory that you defined previously. You can use FTP to easily transfer music from your PC to that folder in the N900. After you put some music,  generate the MPD database:

sudo /usr/local/bin/mpd --create-db

Now we can start MPD with this:

sudo /usr/local/bin/mpd /home/user/.mpdconf

Test that everything is working:

mpc update
mpc add /
mpc play

If you hear music, then everything is great. You can stop the music with:

mpc stop

You can now delete the temporary files we used for the compilation:

cd
rm -r tempdelme

OK, so now MPD is installed on your N900. You can connect with any client to it. Actually, we just connected with one of them, mpc, a console client for MPD.

If you are using firefox, you can use Music Player Minion. If you have an IPod/IPhone/IPad/etc… you can use MPoD. There are many clients for MPD, virtually for any device that you may have at your house.

Enjoy playing with your cool new wireless home sound system.

The last (optional) step is to launch MPD automatically when you power up your phone. The N900 uses upstart to control the boot scripts, so let’s create an upstart script for MPD:

sudo nano /etc/event.d/mpd

In that file, write the following:

start on started hildon-desktop

script
exec /usr/local/bin/mpd /home/user/.mpdconf
end script

stop on starting shutdown

That’s it. Reboot your phone and MPD should be running. You can check it by using the same music test from before, or directly looking at the process:

ps aux | grep mpd

If it says something like this:

1630 user     46276 S    /usr/local/bin/mpd /home/user/.mpdconf
1642 user      2088 S    grep mpd

It means that MPD is running. If on the other hand only the second line appears, it means it is not running.

You can close MPD by killing the process like this:

killall mpd

Finally, note that depending on your battery saving settings your N900 may disable wifi connections initiated from outside (like your SSH or FTP connections) after some inactivity time. You can make sure that the wifi connection keeps open by just pinging the router:

sudo ping 192.168.0.1

Enjoy.

Posted in General, Open Source, Programming.