Showing posts with label raspbian. Show all posts
Showing posts with label raspbian. Show all posts

Sunday, March 17, 2013

Linaro + opencv + exercise

Exercises with Ubuntu-Linaro

1º Load an image

2º Contours

libjpeg libjpeg-turbo Linaro
Load 199 63126
2Gray 61 4557
Trheshold 12 12 12
Create 32 11 10
find 53 3171
Draw 47 47 87
Total 404 209363



 3º Search one pattern

libjpeg-turbo Linaro
Load Source 11 6
Load Pattern 11 6
Search 488 487
Total 510 499

4º Haar-Features

The time is quite similar

Conclusion 

The ubuntu-linaro is a little bit more fast, but it'snt a big difference.

I prefer to use raspbian cause it has a big community, and the information it's easy to find, and may be it has more things that I need, but I feel comfortable  in raspbian than in ubuntu-linaro.

But I know that I'm not taking all the power of the cubieboard, I've in mind to improve the compilation using cross compilation, and take advantage of the NEON acceleration, but I'll do latter when I've more knowledge 

Monday, February 25, 2013

libjpeg vs libjpeg-turbo

With the first exercise I've the opportunity to compare libjpeg vs libjpeg-turbo.

Before to install libjpeg-turbo I made a backup with the standard one, so it's a great moment to compare both

The code used is the same in both cases (Contours) and here are the results

libjpeg-turbo

libjpeg

libjpeg libjpeg-turbo
Load 199 63
2Gray 61 45
Trheshold 12 12
Create 32 11
find 53 31
Draw 47 47
Total 404 209

Finally the libjpeg-turbo is faster than libjpeg, we will check in the future what happen with Linaro vs Raspbian.

By the moment I'll be working with Raspbian with libjpe-turbo

Saturday, February 23, 2013

Contours in openCV

Detecting contours.


The process of detecting contours is one of the simples.

Load the image -> Change to gray --> use the threshold function --> find the contour --> draw the contours

The code

//Load the image in colour
        flag=(double) getTickCount();
        imagen=imread(argv[1],CV_LOAD_IMAGE_UNCHANGED);
        flagLoad=getTick(flag);
//Change the image to gray
        flag=(double)getTickCount();
        cvtColor(imagen,imgGris,CV_BGR2GRAY);
        flag2Gray=getTick(flag);
//use the threshold to separate few objects
        flag=(double)getTickCount();
        threshold(imgGris,imgContorno,122,255,THRESH_BINARY);
        flagThreshold=getTick(flag);
//we need a place to leave the new iamge
        flag=(double)getTickCount();
        Mat dst = Mat::zeros(imgGris.rows,imgGris.cols,CV_8UC3);
        flagCreate=getTick(flag);

        namedWindow("gris",CV_WINDOW_NORMAL);
        namedWindow("contorno",CV_WINDOW_NORMAL);
        namedWindow("binario",CV_WINDOW_NORMAL);

        imshow ("gris",imgGris);
        imshow ("contorno",imgContorno);
        cvMoveWindow("gris",300,50);
        cvMoveWindow("contorno",600,50);

vector< vector<Point> > vecContornos;
vector<Vec4i>jerarquia;
//Find the contours
        flag = (double)getTickCount();
        findContours(imgContorno,vecContornos,jerarquia,CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE);
        flagFind =getTick(flag);
        flag = (double)getTickCount();
        for (int idx=0;idx >=0;idx=jerarquia[idx][0])
        {
                drawContours(dst,vecContornos,idx,WHITE,5,8,jerarquia);
        }

The results 

And finally we have this results from the original image


Original image


Result image
 All the values are in milliseconds 

This exercise give us a useful information

The main information is the threshold to separate the right image (12 ms) and find the contours (31 ms) around 50 ms to detect objects, it's not really bad for a dive which could use this information.

But the structural analysis could be take more time, we will what happen in the next exercises 

Any comment will be appreciated

Friday, February 22, 2013

Raspbian + OpenCV + libjpeg-turbo

A few time I made the installation of openCV over Raspbian, but after speak at the Cubieboard community there is a library called "libjpeg-turbo" wich is faster than the standard one

I  read a lot of information about it, and as far I know, the Linaro distribution use it, (I've to do a double check)

But at this moment I can't take off the raspbian and I've to install the library separately

I found one article that explain what to do
How to compile  the OpenCV 2.4.0 with libjpeg-turbo
To build OpenCV 2.4.0 with libjpeg-turbo you need:
  1. build libjpeg-turbo as static library
  2. configure OpenCV with the following command:
    cmake -DWITH_JPEG=ON -DBUILD_JPEG=OFF -DJPEG_INCLUDE_DIR=/path/to/libjepeg-turbo/include/ -DJPEG_LIBRARY=/path/to/libjpeg-turbo/lib/libjpeg.a /path/to/OpenCV

But I'm a little bit out of training and find some questions.
So what I've to do ? I need a cook book, and I didn't find so I have to make one. (please any mistake let me know)

1º Download the libjpeg-turbo

Master of libjpeg-turbo :https://github.com/aumuell/libjpeg-turbo/archive/master.zip

To make the installation ( follow the installation)
2º Prepare the installation

unzip libjpeg-turbo-master.zip 
cd {source_directory}
autoreconf -fiv 
(note: if the autoreconf doesn't exist add it "sudo apt-get install dh-autoreconf")
mkdir {build directory}
#cd {build_directory} sh {source_directory}/configure [additional configure flags}
../configure --enable-static
 2-Bº After made the configuration we need to make the library static. (How I can make a static library :| ) -->
"-fPIC" which was an abbreviation for Position Independent Code, and this had 
to be passed to create library code objects, without that flag, code that is specific to 
the source would be used, and then the library would fail.

The  command "../configure --enable-static" will create some files
We have to edit the “Makefile” 
Locate the line CC = gcc 
and change it by CC = gcc -fPIC
sudo make
sudo make install.
After all this steps we'll have installed the libjpeg-turbo. 3º Now How to link our OpenCV to libjpeg-turbo ? Its easy we have to create again our CMAKE configuration
#I removed the python compatibility 
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_EXAMPLES=ON 
-DWITH_JPEG=ON -DBUILD_JPEG=OFF 
-DJPEG_INCLUDE_DIR=/path/to/libjepeg-turbo/include/ 
-DJPEG_LIBRARY=/path/to/libjpeg-turbo/lib/libjpeg.a /path/to/OpenCV .. 
 

When the CMAKE comand is done we will see somthing like that

- Detected version of GNU GCC: 46 (406)
-- Found JPEG: /opt/libjpeg-turbo/lib/libjpeg.a  
-- Found Jasper: /usr/lib/arm-linux-gnueabihf/libjasper.so (found version "1.900.1") 
-- Found OpenEXR: /usr/lib/libIlmImf.so
-- Looking for linux/videodev.h
-- Looking for linux/videodev.h - not found
-- Looking for linux/videodev2.h
-- Looking for linux/videodev2.h - found
-- Looking for sys/videoio.h
-- Looking for sys/videoio.h - not found
-- Looking for libavformat/avformat.h
-- Looking for libavformat/avformat.h - found
-- Looking for ffmpeg/avformat.h
----------------
-- 
--   Media I/O: 
--     ZLib:                        /usr/lib/arm-linux-gnueabihf/libz.so (ver 1.2.7)
--     JPEG:                        /opt/libjpeg-turbo/lib/libjpeg.a (ver 80)
--     PNG:                         /usr/lib/arm-linux-gnueabihf/libpng.so (ver 1.2.49)
--     TIFF:                        /usr/lib/arm-linux-gnueabihf/libtiff.so (ver 42 - 4.0.2)
--     JPEG 2000:                   /usr/lib/arm-linux-gnueabihf/libjasper.so (ver 1.900.1)
--     OpenEXR:                     /usr/lib/libImath.so /usr/lib/libIlmImf.so /usr/lib/libIex.so /usr/lib/libHalf.so /usr/lib/libIlmThread.so (ver 1.6.1)


make
#we have to wait a little bit (you can stop and continue later)

sudo make install 
 

Monday, February 18, 2013

Repeat the exercises

Next exercises 

A few time ago I made some exercises to study  computer vision, and I have to repeat them.
I made it with my computer I3 and 6 GB of RAM, I have to recognize that the code were a little bit dirty (not very efficient)

But if I can show the expected results, and I will give a better idea what I want to do with the cubieboard.

.-Detect and follow

This exercise consist in to take a part of an image, the eye in this case, and detect and follow.


.- Contours.

One of the most important this is to detect different contours, center of object.


.- Blobs
Blobs are pixels continuous quite similar to be the same piece








Saturday, February 16, 2013

I need a backup

How to do a backup?

Well we have our micro SD working fine, with all the libraries that wee need

As could be the OpenCV library, but I have to try to modify the compilation that I made in Cubieboard + openCV, and we have a small risk to make some mistake and the process to install should to start.

To avoid this problem, I am going to do a backup of the micro SD, it is quite simple in Linux. I don't know Windows, but if some can do it please leave a comment.

.- Take out the micro SD and with an USB adapter connect to the computer

ikaro@nirvana ~ $ dmesg
[ 2298.045043] sd 3:0:0:0: [sdc] 15548416 512-byte logical blocks: (7.96 GB/7.41 GiB)
[ 2298.050815]  sdc: sdc1 sdc2
[ 2298.053659] sd 3:0:0:0: [sdc] Attached SCSI removable disk

The card has two partitios

ikaro@nirvana ~ $sudo fdisk /dev/sdc

Disk /dev/sdc: 7960 MB, 7960788992 bytes
245 heads, 62 sectors/track, 1023 cylinders, total 15548416 sectors
   Device Boot      Start         End      Blocks   Id  System
/dev/sdc1            2048      131071       64512    e  W95 FAT16 (LBA)
/dev/sdc2          131072    15548415     7708672   83  Linux

So we want to duplicate the micro SD

With all this information we can continue to clone / duplicate / backup

ikaro@nirvana ~ $ dd bs=1M if=/dev/sdc of=raspbery_Cubie.img

I have tried with bs=4M but the backup did not work.
This command take a few minutes.

But finally will have our backup from the micro SD

ikaro@nirvana ~/backup_cubieboard $ ls -lh
total 7,5G
-rw-r--r-- 1 ikaro ikaro 7,5G 2013-02-16 10:40 raspbery_Cubie.img.

Now we have to put this image into a new micro SD, at last of the same size and we can put the image into it

ikaro@nirvana ~ $ dd bs=1M  if=raspbery_Cubie.img of=/dev/sdc

And we will have the backup done.

I know it is a process simple, but it very useful

And if you want to make a NAND Flash backup it quite easy too, from raspbian.

 dd if=/dev/nand of=/some/place/with/enough/space

Sunday, February 10, 2013

Load an Image


First step with OpenCV (corrected)

Load an image, Lena is here.

I made this exercise a few weeks ago, but I had a mistake, and the obtained data were not correct, the first test gave me around 140 milliseconds to load and display an image.

To much time if we think that in one second of video, we could have till 30 images per second or even more; one image each 33 miliseconds.

Note: This comparative it is not real, the video has a different compression such as I-Frames (real images) and P-frames( predictive frames)


There are a more things to do as looking for libjpeg-turbo, change the Raspbian to Linaro

But the first thing to do is to correct the code, and separate each time in their different process: Load the image, display the image

This is the new code.

#include <cv.h>
#include <highgui.h>
#include "../00_include/tools.h"

using namespace cv;

int main (int argc, char** argv)
{
Mat imagen;
double flag,flagCarga,flagDisplay, tiempo;
char resultadoCarga[25];
char resultadoDisplay[25];
char resultado[25];
Size imgSize;
//flag of time
        flag =(double)getTickCount();
        imagen=imread(argv[1],CV_LOAD_IMAGE_UNCHANGED);
//calculate the time
        sprintf(resultadoCarga,"Load %2.f",getTick(flag));
        namedWindow("FOTO",CV_WINDOW_AUTOSIZE);
//Fetch the size
        imgSize = imagen.size();
        sprintf(resultado,"Size width=%d height=%d",imgSize.width,imgSize.height);
//New flag of time
        flag = (double)getTickCount();
        imshow("FOTO",imagen);
//calculate the time
        sprintf(resultadoDisplay,"Display %2.f",getTick(flag));
        printf("%s\n",resultadoDisplay);
//put the data on the image
        putText(imagen,resultadoCarga, Point(10,20),FONT_HERSHEY_SIMPLEX,0.5,BLUE,1);
           putText(imagen,resultadoDisplay,Point(10,35),FONT_HERSHEY_SIMPLEX,0.5,BLUE,1);
        putText(imagen,resultado,Point(10,50),FONT_HERSHEY_SIMPLEX,0.5,BLUE,1);
//Save the image
        imwrite("out.jpg",imagen);
        waitKey();
}


Well, with the correct software we have this values on the photo.


The values are:
.- Load 41 milliseconds
.- Display: 5 milliseconds

Well this values are no too bad, but it is not computer vision, we did not anything with the image as could be check the blobs, detect a face, and eye, some color, detect objects, etc.

Aprender sin reflexionar es malgastar la energía. Confucio (551 AC-478 AC).
Learning without thinking is labor lost. Confucius (551BC - 478 BC)

We can see that we have 41 miliseconds to charge an image, so we would check with libjpeg-turbo, and we will see if the load time get reduced, try to use and SATA HD.
 The display time was 5 milliseconds, if its computer vision, we do not need see the image, just the cubieboard has to "see" it and process. 

This exercise does not give us to much information cause is not related with computer vision.
I will have better information wen have time to make the exercises about computer vision as detect contours, geometry, detect faces, eyes, blobs (contiguous pixels with similar color), etc.

But one important thing is to try Linaro, but I can not do it at this moment, I have to wait a couple of weeks


There is a very interesting information that I learned at the Cubieboard community


getTick(flag)

 double getTick(double flag)
{
/*
This functions return the time in milliseconds
since the "flag" moment till now
*/ 
//Get the frequency  
double frecuencia = getTickFrequency() / 1000 ;
double t = (double)getTickCount();
return((double)t - flag)/frecuencia;
}


 



Saturday, January 19, 2013

Cubieboard + OpenCV


¿Qué es la visión artificial?

Cuando un ordenador procesa una imagen, no entiende lo que realmente se ve en ella.
Pero y si necesitamos detectar una persona, o una cara en concreto, o un objeto, o seguir un color, o encontrar una forma, interpretar lo que vemos, etc.
De todo esto se encarga la visión artificial.

¿Cómo aplicamos la visión artificial?

Bueno aquí es donde viene en nuestra ayuda OpenCV, es un conjunto de librerías que nos permite abstraer al programador de la parte más laboriosa de la programación y utilizar funciones ya preparadas para todas las necesidades que tengamos.
Hay posibles instalaciones para Linux, android, windows, ios

Instalando OpenCV


He sacado toda la información técnica de este blog, muy bueno, no solo por este artículo sino por muchos otros.

Fuente: http://mitchtech.net/raspberry-pi-opencv
Fuente: http://docs.opencv.org/doc/tutorials/introduction/linux_install/linux_install.html#linux-installation

Raspbian : Linux raspberrypi 3.4.19-a10-aufs+
OpenCV: OpenCV-2.4.3.tar.bz2 (os recomiendo entrar y descargar la última versión)
http://OpenCV.org

¿Quizas antes de hacer la instalación deberías decidir si libjpeg o libjpeg-turbo?
May be if you are reading this you should to think libjpeg or libjpeg-turbo?
  1. ¿Dónde vamos a hacer la instalación?
    1. Tarjeta ¿Hay espacio?, Con 2 GB suficiente pero mejor una de 8GB (que luego ya iremos necesitando)

      S.ficheros     Tamaño Usados  Disp Uso% Montado en
      rootfs           7,3G   1,5G  5,5G  22% /


      NOTA: Se hace un poco lenta, pero funciona

      ¿Por qué sobre la tarjeta? En el futuro quiero que esta placa sea el "razonador lógico" (no me gusta la definición inteligencia artificial), además de portátil debe consumir poco y un disco duro por muy ligero que sea, tiene un consumo muy alto para baterías (1A a 5 V)
  2. Descargar la última versión
    1. Yo instale esta OpenCV-2.4.3.tar.bz2  de todas formas buscar la última versión.
  3. Dependencias
    Bueno para hacer la instalación necesitamos hacer nuestra máquina con una base de herramientas necesarias. Describir cada una de ellas se escapa de este blog, pero las más interesante es cmake que nos permitirá configurar nuestra compilación e instalación.

    sudo apt-get -y install build-essential cmake pkg-config libpng12-0 libpng12-dev libpng++-dev libpng3 libpnglite-dev zlib1g-dbg zlib1g zlib1g-dev pngtools libtiff4-dev libtiff4 libtiffxx0c2 libtiff-tools

    sudo apt-get -y install libjpeg8 libjpeg8-dev libjpeg8-dbg libjpeg-progs ffmpeg libavcodec-dev libavcodec53 libavformat53 libavformat-dev libgstreamer0.10-0-dbg libgstreamer0.10-0 libgstreamer0.10-dev libxine1-ffmpeg libxine-dev libxine1-bin libunicap2 libunicap2-dev libdc1394-22-dev libdc1394-22 libdc1394-utils swig libv4l-0 libv4l-dev python-numpy libpython2.6 python-dev python2.6-dev libgtk2.0-dev pkg-config
  4. Ahora vamos por pasos a instalar
    1. Nuestro directorio OpenCV con su versión OpenCV-2.4.3.tar.bz2

      tar -xvjpf OpenCV-2.4.3.tar.bz2
      rm OpenCV-2.4.3.tar.bz2
      cd OpenCV-2.4.3.tar.bz2
      mkdir build
      cd build

    2. Preconfigurando la compilación
      Con esto le diremos que nos compile lo que necesitemos, con este se crea una instalación bastante estándar, además de instalar el soporte para python


      cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_PYTHON_SUPPORT=ON -D BUILD_EXAMPLES=ON ..

      make
      sudo make install

  5. Últimos pasos
    1. Unas configuraciones para indicar las bibliotecas y librerías.

      $ sudo vi /etc/ld.so.conf.d/opencv.conf

      Si no existe lo creamos y añadimos la siguiente línea

      /usr/local/lib

      Configuramos el enlace dinámico de las librerías

      $sudo ldconfig -v

    2. Configuramos el sistema de bashrc de modo global

      sudo vi /etc/bash.bashrc
      Y añadimos la siguiente línea

      PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig export PKG_CONFIG_PATH
  6. Probando OpenCV
    1. Nos vamos al directorio de ejemplos de C
      ~/OpenCV/OpenCV-2.4.3/build/bin

      convexhull

      kmeans

      drawing

Hull

Cluster


Dibujos



Siguientes pasos

Wednesday, January 9, 2013

Vaso Medio lleno, vaso medio vacio, o ... sobra vaso

Bueno ahora ya hemos visto que nuestra cubieboard es más lenta en procesamiento que un dos nucleos (cielos y tanto estudiar para esto :S)
¿Pero eso realmente significa que es malo ?

¿ Realmente cuanta potencia necesito ?

Para contestar esa pregunta hay que hacer otra pregunta.

¿Qué vamos a hacer ?

Algún ejemplo
Por ejemplo el software de  cabina del space shutthle (1981) (transbordador espacial ) funcionaba con un intel 8086 y luego fue un 80386.
Los equipos de la estación internacional espacial (ISS) usan para los comandos  un 80386.
http://www.gratisprogramas.org/descargar/los-cpu-de-las-naves-espaciales-computadoras-en-el-espacio/

Ahora si queremos jugar al Angrybirds igual necesitamos algo más.

¿Qué voy a hacer?

Una vez visto los ejemplos me tendré que centrar en lo que yo quiero hacer.
  1. Visión artificial con Opencv (umm igual se me queda corto, pero estamos hablando de una plataforma de estudio)
  2. Manejo y comunicación con arduinos
  3. Estudiar temas de Inteligencia artificial para problemas racionales. (aquí estoy algo verde)
Bueno pues ya tengo tarea para estudiar.
Iré poniendo los temas de las cosas que vaya aprendiendo.

¿Que tarjeta de memoria le pongo?

Tarjeta de memoria.

Bueno tenemos que hacernos con una tarjeta microSD para empezar, pero cual.

Por casa tenía una tarjeta de 8GB clase 4, pero siempre uno quiere algo más de velocidad, así que compre una tarjeta Sandisk Ultra 16GB y ejecute una prueba de velocidad de acceso a la tarjeta.

8 GB Clase 4

16GB  Clase 10 UHS-I
Así que la velocidad que ganamos es, ummm no mucha, pero bueno es más grande y ya puedo empezar a cargar al Raspbian de cosas, pero lo mejor será en pensar en un disco duro.

NOTA: Al instalar Linux no se pierde la memoria NAND donde está Android


Problemas(más vale tarjeta vieja que arranca, que nueva y rápida que no arranca)

No todo el monte es orégano, la nueva tarjeta de Sandisk Ultra 16GB, tiene un comportamiento anómalo.

Instalo sin problemas el berryboot, y luego raspbian, pero una vez terminada la instalación no permite arrancar, viendo por foros he visto que no soy el único

En la comunidad de Cubieboard en google+ se ha comentado y la verdad he tenido que darles la razón, cambiando de tarjeta funciona y como la tarjeta de 8GB y clase 4, tampoco es que de un peor resultado apreciable, continuaremos con la tarjeta "antigua"

Saturday, January 5, 2013

Primeras pruebas

Probando, probando 1,2,3.....¿Cuántos Kflops?

Bueno, ya tenemos todo instalado ahora vamos a probar que tenemos entre manos.


¿Qué equipo tengo ?

Vamos probando un lscpu
 
pi@raspberrypi ~ $ lscpu
Architecture:            armv7l
Byte Order:               Little Endian
CPU(s):                        1
On-line CPU(s) list:  0
Thread(s) per core: 1
Core(s) per socket:   1
Socket(s):                    1

¿Y de memoria? ¿Cómo ando?

pi@raspberrypi ~ $ cat /proc/meminfo
MemTotal:         834892 kB
MemFree:          381636 kB
Buffers:           85808 kB
Cached:           285972 kB

¿Y si nos marcamos un benchmark ?

Vamos a hacernos unas cuantas operaciones algo rapidito, que hay cosas que hacer.

Con la aplicación de HardInfo de linux :) saldremos del paso, y así podremos comparar con ordenadores conocidos.


CPU Blowfish

 Cubieboard    1000 MHz     46,346
I3    1197 MHz        4,009
Intel(R) Celeron(R) M processor 1.50GHz (null)  26.1876862
PowerPC 740/750 (280.00MHz)     (null)  172.816713
 (medido en segundos, mejor cuanto más bajos)

CPU Fibonacci

Cubieboard    1000 MHz     14,525
I3    1197 MHz        2,796
Intel(R) Celeron(R) M processor 1.50GHz (null)  8.1375674
PowerPC 740/750 (280.00MHz)     (null)  58.07682
 (medido en segundos, mejor cuanto más bajos)

Bueno si lo comparamos con un celeron no está tan mal
Aunque parezca poca cosa, estamos hablando de un buen procesamiento, seguro que podremos sacarle mucho jugo y como plataforma de estudio está muy bien.

Instalando Linux 2/2

Instalación de Linux

Partimos del paso anterior, donde habíamos instalado el berryboot (gestor de arranque ) en nuestra tarjeta uSD.
Hacemos reset a nuestra cubieboard (dejando la tarjeta insertada) y nos arrancará el gestor berryboot
  1. Arrancamos con la tarjeta uSD
  2. Nos arranca el berryboot para hacer la primera instalación. (se pueden tener varias distribuciones de Linux en una misma tarjeta)
  3. Configurar el acceso a internet (en mi caso fue la wifi)
  4. Nos pide sobre que soporte vamos a hacer la instalación, usaremos la uSD.
  5. Nos da a elegir entre una serie de distribuciones, según nuestras necesidades.
  6. Yo elegí por tema de programación y sistemas la raspbian, la versión de Debian para raspberry
  7. Nos descargará la distribución elegida y nos la instalará en nuestra tarjeta.
  8. y a disfrutar

Se puede conectar vía wifi

¿Cuál elijo ? :|

La guardamos en la tarjeta


Esperamos, pero no mucho

y voilá, aquí tenemos nuestra raspbian

Arrancando
Raspbian en la cubieboard