Tuesday, June 29, 2010

Preparando la cancion de Giovani Dos Santos



El partido del domingo donde jugo Mexico-Argentina (disculpen la falta de acentos estoy en una maquina anti latina :( Sufri una gran depresion. Aunque sigo creyendo en la actitud que tiene Giovani Dos Santos y Chicharito. Ellos realmente me inspiran a trabajar mejor. Digo si estos chiquillo se estan rompiendo su madre en su trabajo, como yo no voy a hacer lo mismo en el mio?

Espero que se aprenda de errores de este mundial y el proximo mundial contemos con un mucho mejor tecnico. Me molesta esa situacion porque creo que se tenia talento pero no se supo aprovechar.

En fin sigamos adelante...
Cabe se~alar que estoy muy emocionada por el encuentro Argentina-Alemania. Quiero decir que admiro mucho toda la cultura de futbol que tiene alemania. Amo sus canciones futboleras. Me parecen motivantes.Alzan el espiritu!
Voy a compartir una las canciones futboleras alemanas que mas me agrada, tal vez la letra no es tan espiritual ( Hay otras que si lo son) pero en lo personal me divierte y me pone de buen humor.

! Los geht's Deutschland, kämpfen und siegen!






Das Lu Lu Lukas Podolski Lied
Poldi Poldi Halleluja
Poldi Poldi Halleluja
Poldi Poldi Halleluja
Es gibt einen Fußballgott

Manche Spieler, die sind einfach schwach
Du regierst den Ball und hälst ihn flach
Manche, die sind faule Millionäre
Doch dir geht es einfach um die Ehre

Nach dem Spiel ist wieder vor dem Spiel
Und läuft es auch mal nicht so, wie man will
Wirst du trotzdem immer alles geben
Denn für dich bedeutet Fußball Leben
Lu-Lu-Lu-Lukas Podolski
Lu-Lu-Lu-Lukas Podolski
Lu-Lu-Lu-Lukas Podolski
Lu-Lu-Lu-Lukas Podolski
Lu-Lu-Lu-Lukas Podolski

Wichtig ist ganz einfach auf'm Platz
Alles andere ist doch Ersatz
Du bist jung und du bist wild
Manchen Torwart hast du schon gekillt
Die Fans, die singen "Lukas, WE LOVE YOU"
Ja, du hast echt den Goldnen Schuh
Komm und mach das Dingen endlich rein
Denn dann singen alle im Verein:
Lu-Lu-Lu-Lukas Podolski Lu-Lu-Lu-Lukas Podolski
Goldi Poldi Halleluja
Goldi Poldi Halleluja
Goldi Poldi Halleluja
Es gibt einen Fußballgott
(Der Angriff läuft über rechts,
geht über links,in die Mitte,
in der Mitte steht wer?)
Lu-Lu-Lu-Lukas Podolski
Lu-Lu-Lu-Lukas Podolski
Lu-Lu-Lu-Lukas Podolski
Lu-Lu-Lu-Lukas Podolski
(Die 90. Spielminute läuft,
der Ball kommt aus dem Mittelfeld,
schießt zu Poldi,Poldi steht frei
vor der Hütte -Tooor!!!)


La cancion de Lu Lu Lukas Podolski
Poldi Poldi Halleluja
Poldi Poldi Halleluja
Poldi Poldi Halleluja
Existe un dios futbolero.
Muchos jugadores son simplemente muy chafas
Tu dominas el balon y lo puedes sostener como una tabla. Muchos son unos millonarios huevones.
Y si, la neta, la tierra gira simplemente alrededor tuyo.
Despues del juego es antes del juego *
Y a veces las cosas no pasan como uno quisiera, pero a pesar de ello, tu siempre daras tu maximo ya que para ti la vida es Futbol!
Lu-Lu-Lu-Lukas Podolski
Lu-Lu-Lu-Lukas Podolski
Lo importante es quedar en primer lugar, lo demas ciertamente es pura compensacion.
Tu estas joven y estas bien loco.
Ya te haz matado a muchos porteros
Los Fans te cantan: "Lukas, WE LOVE YOU"
Si, la neta tu tienes el zapato de oro.
Ven y haz que las cosas queden por fin perfectas y asi despues toda la sociedad te cantara:
Lu-Lu-Lu-Lukas Podolski
Lu-Lu-Lu-Lukas Podolski
Lu-Lu-Lu-Lukas Podolski
Lu-Lu-Lu-Lukas Podolski
Goldi Poldi Halleluja
Goldi Poldi Halleluja
Goldi Poldi Halleluja
hay un dios futbolero

(la ofensiva corre hacia la derecha, se va a la izquierda y en medio, y en medio quien esta?!)
Lu-Lu-Lu-Lukas Podolski
Lu-Lu-Lu-Lukas Podolski
Lu-Lu-Lu-Lukas Podolski
Lu-Lu-Lu-Lukas Podolski
(Al minuto 90 la pelota llega a medio,se la lanzan a Poldi,Poldi queda enfrente de la porteria-Goool!!! )




Aquí está la rolita:


Y aquí hay algunas notas acerca de algunas cosillas que menciona la canción:
Nach dem Spielt ist vor dem Spielt==despues del juego es antes del juego, esta es una frase que surgio de un entrenador de futbol aleman. Que me parece llevo al equipo a la gloria en un mundial. Lo que significa la frase es que una vez que haz terminado de jugar un partido, ya estas pensando y preparandote para el siguiente partido que jugaras.
Espero disfruten estas canciones alemanas, ojala alguien me pueda ayudar a hacer una cancion similar para Giovani Dos Santos. Aunque no se vale invitar a Belinda. Mejor libre solterito sin apuros ;) haha :P
Pondre una foto de Giovani, mostrando su coraje y como tambien merece su cancion:



Tuesday, May 18, 2010

Support Vector Machine Tutorial with OpenCV 2.1 for Dummies

Debido al enorme tiempo que me tomó poder hacer este pequeño código, decidí escribir el código en mi blog y ayudar así a futuras personas que de pronto se atoren con algo similar. "what comes around goes around".
¿Que fue lo que me atormento desde el Domingo por la noche?

Poder utilizar la librería de aprendizaje de máquina que proporciona la nueva versión 2.1 de OpenCV para tener un clasificador de tipo "Support Vector Machine" . ( No tengo la menor idea de cómo se dice, Support Vector Machine en español , Lo podría buscar, pero no he dormido bien en los últimos días..., Entonces al lector que lo averigue y me lo haga saber, ganará un regalo especial de este blog =)

Así que el propósito de este post, será tener el clasificador corriendo. Para ello, asumiremos que sólo tenemos dos clases, las cuales tienen las etiquetas de -1 y 1.
Cada clase tiene elementos, estos elementos son puntos en 2D.
La clase 1 asumiremos que tiene los siguientes elementos:
3,2.5
6,5.5,
La clase 2 tiene:
-5,5.5
-7,6
-8,-3
Lo unico que probaremos es tener un clasificador que si le envió 3, 2.5 diga: Clase 1 B-)

En C++ y usando la librería de opencv, esto se traduce a :


#include "highgui.h"
#include "cv.h"
#include "ml.h"
#include "cxcore.h"
#include "cxtypes.h"
//#include "cell.h"
#include "celda.h"
#include
//#include
using namespace std;
using namespace cv;

int main()
{
/*Aqui creamos las posibles etiquetas que existirán, las etiquetas
correspondrán con el número de clases que existen, y el número de etiquetas corresponde con el número de ejemplos de aprnedizaje que existen*/
float array_labels[]= {1.0,1.0,-1.0,-1.0,-1.0};
/*Aqui declararemos los datos que se usarán para entrenar, nótese que estoy diceindo que habrá 5 ejemplos de aprendizaje, cada uno con dos valores, la etiqueta del primer elemento corresponde con la primera etiqueta guardado en array_lables.*/
float array_trainData[5][2] = { 3,2.5, 6,5.5, -5,5.5, -7,6, -8,-3};
/*Creamos matrices de opencv que guardarán estos datos*/
cv::Mat trainData(5,2,CV_32FC1,array_trainData);

cv::Mat labels(5,1, CV_32FC1, array_labels);
/
*Creamos el support vector machine*/
CvSVM SVM;
*Lo entrenamos*/
SVM.train(trainData,labels);

/
*Vamos a probarlo!, tomaremos cada uno de los datos del training set, y veremos si nos da la espuesta correcta*/
for(int i = 0; i <5;>
{
double r;
r = SVM.predict( trainData.row(i) );

cout<<"classified as "<<


}

}


Y eso es todo amigos =)
Si ese pequeño código me hizo tardarme aaaños =(
Para un tutorial de Support vector machines chequen: http://citeseer.ist.psu.ed/burges98tutorial.html
y la libreria de machine learning de opencv puede ser consultada en:
http://opencv.willowgarage.com/documentation/cpp/support_vector_machines.html#cvsvm-train

Nota que este tutorial es de la Ultima version 2.1 de opencv! Creo que es de los pocos tutoriales disponibles en LINEA! and of course it is in spanish =)

...Por cierto, acabo de encontrar esta CANCIÓN POR FIN Youtube, y por el nombre del blog, me parece adequado compartir:

Saturday, April 03, 2010

Das All und dein Lächeln :)


Es viernes de traducción de música alemán. Hoy escuché una de esas canciones cursis en donde recuerdas al amorcino con el convives día a día y te trae tantas sonrisas. No tengo mucho que decir hoy, fue un buen día con muchas sonrisas. Anywho without further a due.




Lass mich nie mehr loss...

Wie New York ohne Sinatra
Wie Wien ohne den Prater
Wie ein Herzschlag ohne Blut
Wie Lindenberg ohne Hut
Wie ne Eiszeit ohne Schnee
England ohne Tee
So als ob bei Steve McQueen die ganze Coolheit fehlt

Jeder Boxer braucht ne Linke,
Kiss braucht viermal Schminke
Tonic braucht Gin.
Wie wär ein Leben ohne Sinn?
Wie ein leeres Paket
Wie ein Rad das sich nicht dreht
So als ob anstatt nem Sturm nur ein leichter Wind weht



So bin ich ohne dich
Du hältst mich mir fehlt nichts
Lass mich nie mehr los
Lass mich lass mich nie mehr los
Lass mich nie mehr los
Lass mich lass mich nie mehr los

Wie das All ohne Planeten
Astronauten ohne Raketen
Paul Newman ohne Clou
Old Shatterhand ohne Winnetou

Wie ein Dieb der nicht stiehlt
Wie ein Wort das nicht zählt
So als ob dem Alphabet ein Buchstabe fehlt

So bin ich ohne dich
Du hältst mich mir fehlt nichts
Lass mich nie mehr los
Lass mich lass mich nie mehr los
Ich lass dich nie mehr los
Lass mich lass mich nie mehr los

Lass mich nie mehr los
Lass mich lass mich nie mehr los
Lass mich nie mehr los
Lass mich lass mich nie mehr los
So bin ich ohne dich
So bin ich ohne dich
So bin ich ohne dich (wie ein Herzschlag ohne Blut)
So bin ich ohne dich (lass mich nie mehr los!)

Lass mich nie mehr los




Ya no me dejes ir

Como Nueva York sin Sinatra.
Como Austria sin Prater
Como un latido de corazón sin sangre.
Como un Glaciar sin nieve.
Inglaterra sin su Té.
Como si SteveMcQueen perdiera toda su actitud cool.
Todo boxeador requiere de un brazo izquierdo.
Kiss requiere de mucho maquillaje.
La quina requiere de la Ginebra.
¿Cómo sería una vida sin sentido?
Como un paquete vacio.
Como una rueda que no gira.
Como si en vez de la tempestad se tuviera tan sólo un viento suave.

Así soy yo sin ti
Tu me abrazas y no me falta nada.
Ya no me dejes ir
Ya no me dejes ir
Ya no me dejes ir.
Ya no me dejes ir.

Como sería el universo sin planetas.
Astronautas sin cohetes.
el Viejo Shatterhand sin Winnetou
Como un ratero que no roba,
como una palabra que no cuenta,
como si al alfabeto una letra le faltara.

Así soy yo sin ti.
Tu me abrazas y no me falta nada.
Ya no me dejes ir
Ya no me dejes ir
Yo ya no te dejaré ir
Ya no me dejes ir
Ya no me dejes ir
Ya no me dejes ir
Ya no me dejes ir
Ya no me dejes ir
Asi soy yo sin ti
Asi soy yo sin ti
Asi soy yo sin tu (Como un latido de corazon sin sangre) Asi soy yo sin ti
(Ya no me dejes ir!)
Ya no me dejes ir






Aquí está la rolita:



Y aquí hay algunas notas acerca de algunas cosillas que menciona la canción:
Prater es un parquecito muy famoso y caracterísitico de Austria
SteveMcQueen era un actor al que le llamaron el Rey del Cool->King of Cool
El Viejo Shatterhand era un personaje ficticio de las novelas del viejo Oeste, era un alemán que tenía de mejor amigo a un indígena llamado Wnnentou

Sunday, February 28, 2010

The hate and love relationships on social networks...

I had recently the "joy" of reading a very interesting articled by Jure Leskovec, Daniel Huttenlocher, and Jon Kleinberg. And since it's a lazy sunday afternoon,I thought I might take the time to comment on my readings. The paper is titled "Signed Networks in Social Media", and this paper studies how the interaction between positive and negative relationships affects the structure of online social networks. They considered that the richness of a social network consists of a mixture of both positive and negative interactions that co-exist in one single structure.
It might be difficult to understand at first what a negative or a positive relationship in a social network is, since the vast majority of social networks only allow for positive relationships. Facebook for example, only permits users to designate who their friends are and state that they like the activity, status, picture etc of an individual. A user for example, is not capable of showing his dislike for another person's activity.
The study they carried out was therefore focused on social networks that do allow for positive and negative relationships.They obtained large-scale datasets from social applications where the sign of each link-positive or negative- could be reliably obtained.The social networks that were studied are:
  • Epinions: an online rating site that lets people give both positive and negative ratings not only on items but also to other raters. It basically has Web of Trust per User: A network of reviewers whose reviews and ratings the user has consistently found to be valuable. It also has a Block List: list of authors whose reviews the user did not find valuable. “... If you encounter a member whose reviews are consistently offensive, inaccurate, or otherwise low quality, you can add that member to your Block List...”

  • Slashdot: An online discussion site that allows users to tag other users as "friends" or "foes". The user can observe the different kind of relationships it holds with each different user. So if a person were to add someone as a friend, he/she would view them as a friend->http://slashdot.org/my/friends. While if you add a user as a foe, you view them as a foe. http://slashdot.org/my/foes
    If a user adds you as their friend, you would view them as a fan http://slashdot.org/my/fans
    If a user adds you as your foe, you would view them as a freak. http://slashdot.org/my/freaks

  • Votes for Wikipedia admin candidate:When a Wikipedia user is considered for a promotion to the status of an admin, the community is able to cast public votes in favor of or against the promotion of this admin candidate. A positive vote is taken as a positive link from the voter to the candidate, and a negative vote as a negative link.

    This paper worked with the 3 datasets stated above and used these datasets along with 2 different theories of signed networks to reason about how different patterns of positive and negative links provide evidence of the different kind of relationships that exist across these networks. The 2 different theories of signed network that were used are:

    Structural Balance Theory: This was a theory that was proposed by Heider (1958) . Balance theory deals with three kinds of entities. The person (P) whose subjective environment we are concerned with, another person (O); and the object (X), which may be a third person.



Balance theory proposes that with three entities, person-another person-object (POX), three sets of relations exist i.e. between P and O; between P and X and; between O and X
Each of the three relations, P-O, P-X and O-X, can have one of two values. You can either 'like' (+) or 'dislike' (-). With three sets of possible relationships, each taking on one of two values (+/-) eight possible states of affairs exist. This theory states that balance state occurs when all sign multiplication of its sentiment relation charges positive.
For example, take the following diagram:

Here we have P, who we can name Pete that likes O, who we will call Olivia. Pete happens to hate hot peppers and chocolate, X. Balance Theory says, that for the relationship of these 3 individuals to be balanced, Olivia would also need to hate hot peppers and chocolate.
Some of the basic guidlines that Balance Theory follows are:
my friend’s friend is my friend
my friend’s enemy is my enemy
my enemy’s friend is my enemy
my enemy’s enemy is my friend

Now, for this paper they started analysis the social networks mentioned above, by comparing if these networks effectively followed the theorems of Balance theory , in this first stage they only considered undirected relationships between individuals, ie they only considered that Pete likes Olivia, but they did not consider whether or not Olivia likes or dislikes Pete. To carry out the comparative,the frequencies of different types of signed triads were taken into account.
They stated that a certain triad was overrepresented when the following occurred:
p(Ti ) larger than p0 (Ti )
Where P(Ti) represents the fractions of triads Ti. (Ti represents the number of triads of type Ti, for example it could represent the number of 3 person relationships whose edges are all POSITIVE) And P0(Ti) is the apriori probability of Ti based on sign distribution.
They also stated that a certain triad was underrepresented,
if p(Ti )less than po(ti) .
They saw that using status theory they were here able to explain much better these social interactions.
Status theory, claims the following:
Considering nodes A and B, a positive edge from A to B means: “I think B has higher status than I (A) do” A negative edge from A to B means: “I think B has lower status than I (A) do”
Thus, the theory of status predicts that if A links positive to B, then “A regards B as having higher status and" and if B links positive to C then " B regards C as having higher status – so C should regard A as having low status and hence be inclined to link negatively to A














The following table presents their findings:



ti referes to the selected triad. count refers to the number of times that particular triad was encountered in the network. P (+): prob. that closing red edge is positive;SG: surprise of edge initiator giving a positive edge (This is, surprise that Pete would give a positive link to Olivia);Sr: surprise of edge destination receiving a positive edge (surprise that Olivia would get a positive link);Bg:consistency of balance theory with generative surprise;
Br: consistency of balance with receptive surprise;
Sg: consistency of status with generative surprise; Sr: consistency of status with receptive surprise.

They also analyzed, mutual back and forth interactions,they noticed here that the principles of balance are more pronounced than they are in the larger portions of the networks where signed linking (and hence evaluation of others) takes place asymmetrically. They noticed that balance-based effects seem to be at work in the portions of the networks where directed edges point in both directions, reinforcing mutual relationships.

They also noticed that positive ties are more likely to be clumped together,while negative ties tend to act more like bridges between islands of positive ties.

Another interesting observation that they made, was that in their real data, an edge that was more embedded tended to be increasingly positive. These findings are consistent with the social-capital theory that states that embedded edges are more “on display" and thus tend to be positive.
The following picture shows these findings. Rnd denotes random signs created from the network, and real denotes the true signs that this network holds.


















Conclusion:

This paper presents a new perspective on how to reason social media sites by interpreting it as interactions between positive and negative relationships.
They also provide good insight with valid results, on to what theory depending on the network, is more fitted on explaining the nature of the network, i.e whether the network is directed or undirected.
I only have one doubt about the paper: They said that "...balance-based effects seems to be at work in the portions of the networks where directed edges point in both directions, reinforcing mutual relationship..", we could take these portions of the network as the community. Other papers, have only been interested in studying the community aspect of social networks, and feel that when in large scale these communities blend into the entire network, true human behavior is lost. Therefore we could question, if their status theory is modeling human behavior accurately.

None the less very interesting article, would highly recommend :)

Wednesday, January 27, 2010

Das bekommt mir nicht! == Eso no me sienta muy bien...





Tengo miles de pendientes, sin embargo quería hacerme un pequeño momento para poner una canción que acabo de conocer a traves de un servicio del cual me enamoré...y sí no es ningún "adult service". El servicio del cual hablo es blip.fm, es una combinación de twitter con youtube y te crea playlists, todo mundo es un DJ con sus comentarios graciosos a las rolas que les laten...
En fin, atraves de ese servicio conocí esta canción, no sé exactamente por qué pero me fascinó. Es una canción alemana y le hago tributo traduciendola al español!
Aquí esta la trAducción de la rola de 2raumwohnung -> translation to spanish
Translation to spanish!
Por cierto, de nuevo doy gracias a mis clases del cele que me permiten hacer esto.
Comentarios de la traducción son bienvenidos, tuve algunas dudas en varias partes de la canción, tonz apreciaría cualquier comentario al respecto...
Enjoy!




Wir Trafen uns in einem Garten
Wir Trafen Uns In Einem Garten, Wahrscheinlich Unter Einem Baum.
oder War´s In Einem Flugzeug, - Wohl Kaum - Wohl Kaum.

es War Einfach Alles Anders, Viel Zu Gut Für Den Moment,
wir Waren Ziemlich Durcheinander Und Haben Uns Dabei Getrennt.

komm´ Doch Mal Auf Ein Stück Kucken, Später Geh´n Wir In Den Zoo.
und Dann Lassen Wir Uns Suchen - Übers Radio.

ich Weiß Nicht Ob Du Mich Verstehst Oder Ob Du Denkst Ich Spinn´,
weil Ich Immer Wenn Du Nicht Da Bist Ganz Schrecklich Einsam Bin.

dann Denk Ich Mal An Was Anderes Als Immer Nur An Dich
denn Das Viele "an Dich Denken" Bekommt Mir Nicht.
am Nächsten Tag Bin Ich So Müde, Ich Pass Gar Nicht Auf. und Meine Freunde Sagen Ich Seh Fertig Aus.

es Hat Seit Tagen Nicht Geregnet, Es Hat Seit Wochen Nicht Geschneit.
der Himmel Ist So Klar - Und Die Straßen Sind Breit. ist Das Leben Wie Ein Spielfilm Oder Geht´s Um Irgendwas?
wir Haben Jede Menge Zeit Und Du Sagst :"na Ich Weiß Nicht - Stimmt Das?"

fahr Doch Mit Mir Nach Italien, Wir Verstehen Zwar Kein Wort aber Lieber Mal Gar Nichts Verstehen Als Nur Bei Uns Im Ort

dann Denk Ich Mal An Was Anderes ...
(... Und Meine Freunde Sagen: "man Siehst Du Fertig Aus")

alle Fenster Haben Gardinen, Ich Geh Alleine Durch Die Stadt.
ich Frag Mich Ob Mich Jemand Liebt, Der Meine Telefonnummer Hat?
warum Immer Alle Fernsehen? Das Macht Doch Dick!
ich Stell Mit Vor Ich Wär´ Ein Fuchs In Einem Zeichentrick







Nos topamos en un jardín.

Nos encontramos en un jardín, talvez fue más bien debajo de un árbol. O fue en un avión-no no

Todo fue simplemente diferente, demasiado bueno para el momento, aunque estábamos un poco confundidos y desde allí nos separamos.
:(
Andale ven a tomarte un pedacito de pastel, después podemos ir al zológico, y dejamos que nos búsquen --por el radio.
Yo no sé si me entiendas, o pienses que estoy loca, Porque siempre que estás lejos, me siento horriblemente sola.
Entonces en vez de estar todo el tiempo pensando en tí, pienso en otra cosa, porque estar pensando mucho en ti, no me sienta muy bien.

Al día siguiente estoy muy cansada, no puedo poner atención a casi nada. Y mis amigos me dicen que me veo acabada!

Desde hace un par de días no ha llovido, desde hace un par de semanas no ha nevado, el cielo está tan frío y las calles están tan amplías, la vida es como una película, o acaso es para otra cosa?

Tenemos ambos un gran cacho de tiempo libre, y tu dices: ah neta? es cierto esto?.

Andale viaja conmigo a Italia, no vamos a entener nadita, pero es mejor no entender nadita a estar en nuestra casa todo el tiempo.

Entonces en vez de estar todo el tiempo pensando en tí, pienso en otra cosa ...(..Y mis amigos me dicen que me veo acabada!)

Todas las ventanas tienen cortinas, camino solitaria por la ciudad.
Me preguntó a mi misma, si me ama ese individuo que tiene mi número telefónico.
Y por qué todos ven la Tele? Te hace verte gordo, no??!
Me imagino como si yo fuera un zorro dentro de una animación.





Aquí está la rolita:

Sunday, January 17, 2010

Rose Mary, she likes berries, believes in Fairies and is in love with Harry

We will explain here, how to carry out the Harris Corner Detector Algorithm in Matlab.
We will divide the task in 2 parts, one part will calculate the corner points of the image, and the other part, will draw small squares around those corner points with the purpose of having a way of displying them to the user.
The part of detecting the corner points of the image is the following:



%we create a function named harris that receives an rgb image
%and the desired k value. We will return a matrix named A that
%has information about whether or not a certain pixel represents
%a corner.
function [A] = harris(rgb, k)


%If we received an RGB image we convert it to Gray Scale.
%We do this, because if we were to work with an RGB image it
%would be necessary to work with 3 channels, the red, green and blue channel, %instead of just one, which is possible with the gray scale image .

if( size(rgb,3) >= 3 )
img = double( rgb2gray(rgb) );
end

%Before , we continue , it is important to recall that in the Harris Corner Detector, %we obtained a weighted sum of squared differences between an area (uv) and %another area that was obtained by shifting the original area by (x,y), and thus we %had the following form:

S(x,y) = \sum_u \sum_v w(u,v) \, \left( I(u,v) - I(u+x,v+y) \right)^2
%w(u,v) represented a weighted sum. It is important to note that I(u + x,v + y) %can be approximated by a Taylor expansion.
I(u+x,v+y) \approx I(u,v) + I_x(u,v)x+I_y(u,v)y
%Where Ix and Iy are the partial derivatives of I.
%Resulting in:
S(x,y) \approx \sum_u \sum_v w(u,v) \, \left( I_x(u,v)x + I_y(u,v)y \right)^2,
%Since we will carry out an operation that involves partial derivatives we need to %carry out a smoothing, because computation of derivatives generally involves a %stage of scale-space smoothing. For this,we will use the convolution of the gray %image with a Gaussian kernel.
So the next steps that we will carry out are:
a) Calculate the partial derivatives with respect to X and to respect to Y of the image. This will give us the gradients with respect to X and with respect to Y.
b) convolve these gradients with a Gaussian Kernel.
The following is our Gaussian Kernel, which will give us blurring on both directions%

g = 1/16 * [1 2 1; 2 4 2; 1 2 1];

%Here we define the Gradients Operators, we will use the Prewitt Gradient Kernel to obtain the gradients. If we pay more attention to this matrix, we notice that this kernel considers that the orthogonal and diagonal pixel differentials equally

dx = [-1 0 1; -1 0 1; -1 0 1]; %Prewitt Gradient Kernel in X
dy = dx';

% We obtain all the partial derivatives in x and y of the image. These are the %Gradient values.
Ix = conv2(img, dx, 'same');
Iy = conv2(img, dy, 'same');
% We obtain a matrix, that will have the product of Ix*Iy for all Ix and all Iy
Ixy= Ix .* Iy;

% We will now obtain the square value of Ix and of Iy and we will obtain a blurring of Ix square,Iy square and of Ixy.The blurring will be carried out by using the gaussian kernel.We need those square values , since let's recall we had the following:
I(u+x,v+y) \approx I(u,v) + I_x(u,v)x+I_y(u,v)y

Which produces the approximation


S(x,y) \approx \sum_u \sum_v w(u,v) \, \left( I_x(u,v)x + I_y(u,v)y \right)^2,


which can be written in matrix form:

S(x,y) \approx  \begin{pmatrix} x & y \end{pmatrix} A \begin{pmatrix} x \\ y \end{pmatrix},
where A is:

A = \sum_u \sum_v w(u,v) \begin{bmatrix} I_x^2 & I_x I_y \\ I_x I_y & I_y^2  \end{bmatrix} = \begin{bmatrix} \langle I_x^2 \rangle & \langle I_x I_y \rangle\\ \langle I_x I_y \rangle & \langle I_y^2 \rangle \end{bmatrix}
%So we calculate the values that are inside this matrix.

Ix2 = conv2(Ix .* Ix, g, 'same');
Iy2 = conv2(Iy .* Iy, g, 'same');
Ixy = conv2(Ixy, g, 'same');


%We now have 3 matrices , Ix2 that hold the values of all the xs in the image, but they are squared and have been convolved with a Gaussian, so all the xto the square values are blurred a bit. It is important to note, that this operation helps to reduce noise. It smooths the image. We have another matrix Iy2 with the ys to the square value and also blurred as well as third matrix Ixy that holds the values of all the x's times their corresponding y. All 3 of these matrices will help us to calculate the Harris corner response that each pixel of the image has.
The Harris Corner response for each pixel will come out of a matrix A, that as we had said before handwas conformed of:
A = \sum_u \sum_v w(u,v) \begin{bmatrix} I_x^2 & I_x I_y \\ I_x I_y & I_y^2  \end{bmatrix} = \begin{bmatrix} \langle I_x^2 \rangle & \langle I_x I_y \rangle\\ \langle I_x I_y \rangle & \langle I_y^2 \rangle \end{bmatrix}
%Where Ix represents the x value of the pixel, and Iy the y value of the pixel. The Harris Corner response %of a pixel will be Mc:
M_c = \lambda_1 \lambda_2 - \kappa \, (\lambda_1 + \lambda_2)^2 = \operatorname{det}(A) - \kappa \, \operatorname{trace}^2(A)
%What our Harris Function will return will be a matrix that will hold the harris corner response for each %one of the pixels that conform the image:



A = (Ix2.*Iy2 - Ixy.^2) - k * (Ix2 + Iy2).^2;

end


We will now write the function that draws a small red square around the detected corner points.

%This function receives the image we wish to detect and draw the corner points of, %it also receives the desired k value to use, and the desired threshold. It is %important to remember that in the Harris corner detector, we consider a corner %to be a corner when the measure of corner response surpasses a certain %threshold. This measure is computed through the determinant and the trace of the % matrix.

function img_h = project1(img, k, threshold)
%We store the original image in img_h, we need to store it, since we will draw the %squares denoting the corners above it.
img_h = img;
%We use the function we had defined above and with it obtain a matrix that holds %all the corner response measures for all the pixels of the image%
M = my_harris(img, k);

%We iterate through the whole matrix
for x = 2 : size( M, 1 )
for y = 2 : size(M, 2)
%If we find a point of the matrix, that has a value above the threshold, then that %point is a corner and we will draw a rectangle on that pixel.
if M(x,y) > threshold
for xpos = x - 1:x+1
img_h(xpos,y-1,1) = 255;
img_h(xpos,y+1,1) = 255;
end

for ypos = y - 1:y+1
img_h(x-1,ypos,1) = 255;
img_h(x+1,ypos,1) = 255;
end
end
end
end

end



We now present a image that was used for this purpose.
The original image is:

And the image with the corners detected is:

Saturday, January 16, 2010

The Harris Marris whose not Ferris post...

In many robotic problems it is necessary for the machine to be able to detect the depth and distance of certain objects sometimes to avoid obstacles and other times to retrieve with precision a certain object from the scene.
To accomplish this, the robot is usually equipped with 2 cameras that take pictures of the environment they are in. These 2 cameras commonly hold a distance from each other, a distance similar to the one we present with our eyes, due to it, the pictures from one camera are slightly shifted with respect to the ones taken by the other camera. This shift is usually denominated disparity and is what the computer uses to know whether an object is close by or far away.
One major problem that the machine encounters while carrying out this task, is how does it detect that the red cup in picture 1 is moved , let's say, 4 cm with respect to where the red cup is in picture 2?
These vision tasks require finding corresponding features across 2 or more views.


Therefore the first necessary step is to find the features of a scene. But how do we do this?

What we can start doing is making image patches.Elements to be matched are image patches of a fixed size..The task is therefore to find the best (most similar) patch in the second image, it is clear that the chosen patch should be very distinctive (there should only be one patch in the second picture that looks similar). One good patch is one that presents large variation in the neighborhood of a point in all directions.
For example Take the following 2 images:








A good patch image patch could be:


while a bad one, because it has many matchings is:


We are looking for stable features over changes of view points. One type of features that maintain this type of characteristic are Corners.
The Harris Corner detector provides a mathematical tool for finding them.
With an image patch, we can have the following cases:
a) The patch represents a 'flat' zone.
b)The patch represents an edge .
c) The patch represents a corner .



A Flat region as we can see from the above image, presents no change in all directions, an edge presents no change along the edge direction, and a corner presents significant change in all directions. This means that if we shift the window of where we are gathering the patch image, we should perceive a large change in appearance.
The Harris Corner Detector gives us a way to determine which of the above cases hold.
But how does it do it exactly???!

The Harris Corner Detector utilizes the following expression:
E (u,v)=∑ W(Xi,Yi)[I1(Xi+U,Yi+V)-I0(Xi,Yi)]^2
W(Xi,Yi) is a window function. Which sets:


I0(Xi,Yi) is the intensity that is present in the pixel located in (Xi,Yi) and I1(Xi+U,Yi+V) is the intensity located in the pixel Xi+U,Yi+V it is called the shifted or displaced Intensity.
It is easy to see that to detect corners, we want points where E(u,v) is very large.
Using Taylor's first order approximation and matrix algebra the above expression can be rewritten as:


Where M is a 2x2 matrix computed from image derivatives.


The classification can be carried out by analyzing the eigenvalues of the M matrix.


The measure of the corner response is actually set by:
R=(determinant of M)+k(trace of M)^2
Determinant of M=λ1λ2
Trace of M=λ1+λ2
K is an empirical constant that varies from .04-.06

For corners R tends to be very large.
For edges, R tends to be a very large negative number.
For flat areas R tends to zero.