Arduino + WebCam = VolumetriaArduino + WebCam = Volumetry
Um dos projectos que tenho trabalhado ocasionalmente nos ultimos meses foi arranjar maneira de medir volumes com material "low-cost"!
Pensei no desafio e comecei a meter mãos ao trabalho e consegui resultados surpreendentes a usar um webcam comum e um arduino com um sensor.
Para começar vamos falar do hardware:
- Arduino + Sharp Distance Sensor GP2Y0A02 (20-150cm) : Devo dizer que pensei que era o mais simples mas falhei redondamente.
Para conseguir resultados aceitaveis (cerca de 1 centimetro de desvio em distancias perto do limite do sensor) tive de seguir um conjunto de procedimentos manhosos isto porque o sensor tende a retornar montes de ruido e assim não temos resultados precisos.
Primeiro faço 10 leituras do valor e determino a media, seguindamente determinamos o limite superior e inferior de valores a partir desta primeira media, exluimos os valores que ultrapassam este valor capturamos mais uns 10 valores e fazemos a media de tudo.
Devo dizer que isto resultou muito bem
float GetAverage(float * _values, uint8_t size) { float avg = 0; for(int i = 0; i< size; i++) { avg += _values[i]; } avg = avg / size; float setMax = avg * 1.15; float setMin = avg * 0.85; float precisionAvg; int counter = 0; for(int i = 0; i < size; i++) { if((setMin < _values[i]) && (_values[i] < setMax)) { precisionAvg += _values[i]; counter++; } } return precisionAvg / counter; }
Para conseguir volumetria usei a biblioteca Emgu e uns quantos filtros para conseguir encontrar os contornos do objecto com base numa mascara. Ou seja temos de ter uma mascara do ambiente de fundo para poder fazer a exclusão do que ja la estava e ficarmos apenas com o novo objecto na imagem. Usamos uns quantos truques de image processing, uns calculos trigonometricos e voilá aqui esta o resultado
One of the projects I have worked occasionally in recent months was finding a way to measure materials volumes with "low-cost"!
I thought about the challenge and started to get down to work and got amazing results using an ordinary webcam and a sensor with an Arduino.
To begin with let's talk about hardware:
- Arduino + Distance Sensor Sharp GP2Y0A02 (20-150cm): I must say I thought it was the easiest but failed miserably.
To achieve acceptable results (about 1 cm of deviation in distances near the limit of the sensor) I have had to follow a set of procedures that's tricky because the sensor tends to return lots of noise and so we do not have accurate results.
First I do 10 readings and determine the average value, then determine the upper and lower limit values from this first average, capture another 10 and make the average of all the values.
I must say it worked really well
float GetAverage(float * _values, uint8_t size) { float avg = 0; for(int i = 0; i< size; i++) { avg += _values[i]; } avg = avg / size; float setMax = avg * 1.15; float setMin = avg * 0.85; float precisionAvg; int counter = 0; for(int i = 0; i < size; i++) { if((setMin < _values[i]) && (_values[i] < setMax)) { precisionAvg += _values[i]; counter++; } } return precisionAvg / counter; }
To achieve volumetric measuring I used Emgu library and a few filters to find the contours of the object based on a mask. In other words we must have a mask from the background in order to make the exclusion of what it already was there and just stay with the new object in the image. We use a few tricks of image processing, some trigonometric calculations and voila here is the result
meo|kinect @ codebits 2011
Mais uma vez o SAPO Codebits 2011 foi bestial, o unico senão foi a minha apresentação de projecto que teve de passar por "pequenas" dificulades.
Bom vou então falar do pojecto e depois da desastrosa apresentação
Meo|Kinect
Um dia antes do concurso vi na pagina do codebits o seguinte post e no post logo a seguir a falarem que estaria la uma equipa da Microsft para dar o suporte necessário!
ora bem: 1+1= meo|Kinect
O objectivo estava decidido, fazer um interface entre o kinect e a meo box usando um pc no meio para fazer a comunicação entre os dois dispositivos
Desde o primeiro dia o Gonçalo Basto (um os membro da minha equipa), estava a fazer uns widgets para a meo box de modo a que pudéssemos explorar ainda mais o uso do kinect. Falamos várias vezes com o pessoal da PT Inovação, Microsoft, sapo.labs teams e gradualmente fomos nos apercebendo que teríamos de mudar de ideias e que a apresentação no Main Stage estava um pouco comprometida. Disseram que não era impossível fazer a apresentação com uma box no palco, e que isso iria dar algum trabalho a organização. E as ultimas palavras que nos deram foi:
- Mantém-te em contacto connosco que nos vamos ver o que podemos fazer, entretanto falem com a organização.
Perdemos bastante tempo de desenvolvimento com estas questões burocráticas.
Mesmo assim conseguimos desenvolver o interface de gestos usando hotspot que iriam enviar comandos para a box. O tempo para terminar o pojecto estava a terminar mas conseguimos ir testar os resultados finais no equipamento de demonstração da PT Inovação.
Foi um sucesso, mas apenas faltavam 4 horas para a apresentação e nada estava feito para nos no palco.
Fomos para o palco para testar tudo 1 hora antes das apresentações e só nessa altura mandaram alguém ir buscar um router a meo com um cabo de rede e uma box. Montaram tudo mas mesmo assim não estava a funcionar.
Falei com o Celso sobre as nossas dificuldades e ele disseque era tarde demais para resolver problemas destes. Eu disse-lhe que andava desde quinta-feira a tentar resolver este problema e expliquei a nossa situação. Ele agarrou no telefone e disse que ia ver o que era possível fazer...mas que não prometia nada.
Estava desesperado....O resto da nossa equipa desmotivada, pensei em desistir, mas alguém da organização apareceu e disse que iriam fazer com que fosse possível apresentar a nossa aplicação.
O Miguel Vicente da Microsoft, a quem a nossa equipa agradece por toda a atenção, esteve sempre a dar-nos bons conselhos e a dizer para não desistir-mos, a PT Inovação estava muito interessada que a apresentação fosse feita e de repente, fez luz e as coisas começaram a acontecer.
A organização moveu o nosso projecto para o ultimo da lista a ser apresentado para dar mais um tempo extra, a PT Inovação enviou um membro da equipa deles para fazer o setup no palco, e ficamos no chão a frente do palco a configurar todo o hardware e a rede para que tudo funciona-se na apresentação, apesar de não estar nada testado e não sabermos se as coisas iriam funcionar.
Acabamos o setup quando faltavam 5 minutos para a nossa vez no palco, o nosso "porta-voz" estava muito nervoso e nos não acreditávamos que tudo pudesse funcionar mas FUNCIONOU!!!, contudo o nosso orador estava sobre uma pressão enorme acreditando que tudo ia falhar diante aquelas 800 pessoas e acabou por não conseguir fazer o melhor discurso na apresentação... bloqueou e só disse palha para encher os 90 segundos... A apresentação que preparamos acerca de fazer da TV Interactiva um novo conceito, falar acerca do reconhecimento de gestos e voz, um novo mercado possível, etc tudo foi deixado de lado e ficamos a ouvir apenas: "como podem ver eu vou-me mexendo e tal, e entrei num menu... isto é porreiro porque até da para fazer exercício..."
A apresentação foi um fracasso, embora tudo estivesse funcional.
Quero então agradecer a toda a organização do codebits que fizeram o impossível acontecer, a equipa da PT Inovação por nos terem dado uma valiosa ajuda (não é todos os dias que metemos um dos top developers de Portugal em MediaRoom, no chão a configurar DNS's), ao Migue Vicente por toda a motivação que nos deu, a para a minha equipa que apesar de grande pressão até se portou bem.
Mais tarde irei publicar aqui o projecto, incluindo vídeos dele a funcionar.
Foi um excelente codebits e um desafio brutal.
SAPO Codebits 2011 was great, as always, but I found my project presentation a "little bit" compromised by some evil events
First of all I will talk about the project itself and then I'll talk about the disastrous presentation.
Meo|Kinect
Probably you don't know what "Meo" is unless you're at Portugal.
Meo is a triple play service provided by Portugal Telecom (the main telco in Portugal). It gives you IPTV, broadband ADSL from 6 to 200Mbps and Voice Service.
To watch IPTV the hardware required is a Router Thomson and a Scientific Atlanta’s KMM3000 IPTV Set or similar model!
These boxes contain a WinCE as base OS with Microsoft MediaRoom. Microsoft MediaRoom is a extremelly closed software with a lot of license policies around it. Only the service providers and special licenced developers have access to the MediaRoom SDK so basically this is a Black Box.
It is possible to send commands that are remote like keys to the box with telnet and send post via an http a request to open applications.
Now that you are more aware of what is the Meo Service I can go on and explain what was my concept:
One day before the contest on the codebits webpage there was a post mentioning that there would be a team helping to develop for this boxes and giving full support, also I saw that a microsoft team would be there too to help on Kinect based projects.
1+1= meo|Kinect
So I was interested in interfacing the kinect gestures with the meo box using a PC in the middle!
Since day one Gonçalo Basto (one of my team members) was doing some widgets for the box in order to explore the kinect use in the box with interactive widgets. We talked several times with PT Inovação, Microsoft, sapo.labs teams and our ideias should be partially changed and the presentation on the main stage seemed a "little bit" compromised. They said that it wouldn't be impossible but would require some work from the organization to do it. "Keep in touch we will try to handle that, also try to talk with the organization".
We put a lot of efford on that part reducing the development time and the solutions were getting delayed time after time.
We got the interface recognizing the gestures using hotspots on the computer screen that would send nice and clean commands to the box and time to end the project was near at the end when I finally went to test it on a test environment with all the required hardware and network configurations.
It was a success. But we were only 4 hours away from the presentation and nothing was done on stage.
We went there to test the main stage environment 1 hour before and they sent someone to put a network cable on the router and do the magic but it wasn't working at all
I talked with Celso about our issues and he said... "that's too late for such things" and I replied that we passed 3 days trying to get someone to help us. Celso grabbed his cellphone and said "I'll see what I can do for you although I can't promise you nothing it's less than a 1 hour for the presentations"...
I was desperate....the team wasn't motivated, I was thinking about giving up, and someone from the organization told me, "we will make that happen"
Miguel Vicente from Microsoft, which I most send kudos to him, was always giving us good advices and telling to not give up, PT Inovação Team was really interested in make that happen too. And suddenly magic things started to happen.
The organization moved our project to the last one on the list so we could win some time, PT Inovação sent a guy to do the set up, and we where literally laid down in front of the stage configuring all the necessary component to make the presentation... even if it was untested.
We finished all the set 5 minutes before our turn on stage and our presentation guys was insecure has I have never saw him. We didn't believe that it would work on stage and IT DID WORK, but our orator was under a lot of pressure believing that it would never work and he was speechless.... all the presentation we trained, all the talk about making Interactive TV a new concept, the speech recognition features, the new market that could be possible to gain with such features... all was left behind and all we heard about it was: "As you can see I can go to the menus, and do some workout as I do it!"
The presentation was a failures dispite the demo worked after all.
I give my sincere thanks to all the Codebits organization to make the impossible happen, to PT Inovação for giving us a big help and for having one of the top techs on MediaRoom in Portugal laid on the ground in front of 800 persons just to help to configure the DNS hosts, to Miguel Vicente for all the motivation he gave us, and to my team that was under a great pressure due to all our missfortune events.
Soon I will publish more about this project including videos of it working.
It was a great codebits and a great challenge.
First DemoA Primeira Demo
Ok, aqui fica a minha primeira demonstração... É so uma coisa simples, basicamente tenho 2 views uma com o VideoStream RGB e outra com o DepthFieldStream.
É um exemplo bastante semelhante ao tutorial do Channel9 com alguma alterações pelo meio. Por exemplo não estou a usar apenas 3 distancias chave para desenhar as cores, em vez disso implementei a coloração em escala de cinzentos dependendo da distancia, assim da um efeito mais agradavel
Aqui esta o video:
Ok, so here is my first demo... Simple stuff, basically I have 2 views, one with the RGB VideoStream and another with the DepthFieldStream.
Pretty similar to the one of the Channel9 tutorial with some minor changes like I'm not using 3 diferent distance keys to draw the colors and implemented a grayscale colouring depending on the distance.... so it becomes a very smooth...
Here's a vid about it
Kinect + Emgu
Sorry about the inactivity but having and a daytime job and girlfriend sometimes leaves us without time.
using Emgu.CV; using Emgu.CV.UI; using Emgu.CV.Structure; using Emgu.Util; using Emgu.CV.CvEnum; using Microsoft.Research.Kinect.Nui; using Coding4Fun.Kinect.WinForm;
haar = new HaarCascade("haarcascade_frontalface_alt_tree.xml");
will populate the the haarCascade object with that file.
kinect.Initialize(RuntimeOptions.UseColor); kinect.VideoFrameReady += new EventHandler(kinect_VideoFrameReady); kinect.VideoStream.Open(ImageStreamType.Video, 2, ImageResolution.Resolution640x480, ImageType.Color);
public Form1() { InitializeComponent(); haar = new HaarCascade("haarcascade_frontalface_alt_tree.xml"); kinect.Initialize(RuntimeOptions.UseColor); kinect.VideoFrameReady += new EventHandler(kinect_VideoFrameReady); kinect.VideoStream.Open(ImageStreamType.Video, 2, ImageResolution.Resolution640x480, ImageType.Color); }
Image kinImage = new Image(e.ImageFrame.ToBitmap());
Image grayframe = nextFrame.Convert();
grayframe.DetectHaarCascade( haar, 1.4, 4, HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(grayframe.Width / 8, grayframe.Height / 8) )[0];
foreach (var face in faces) { nextFrame.Draw(face.rect, new Bgr(0, double.MaxValue, 0), 3); }
imageBox1.Image = nextFrame;
void kinect_VideoFrameReady(object sender, ImageFrameReadyEventArgs e) { Image kinImage = new Image(e.ImageFrame.ToBitmap()); using (Image; nextFrame = kinImage) { if (nextFrame != null) { // there's only one channel (greyscale), hence the zero index Image grayframe = nextFrame.Convert(); var faces = grayframe.DetectHaarCascade( haar, 1.4, 4, HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(grayframe.Width / 14, grayframe.Height / 14) )[0]; foreach (var face in faces) { nextFrame.Draw(face.rect, new Bgr(0, double.MaxValue, 0), 3); } imageBox1.Image = nextFrame; } } }
with good lightning, the detection occurs flawlessly
Descupem lá a inactividade nos ultimos tempos. mas ter um trabalho a tempo inteiro e ter namorada as vezes deixa-nos sem tempo.
using Emgu.CV; using Emgu.CV.UI; using Emgu.CV.Structure; using Emgu.Util; using Emgu.CV.CvEnum; using Microsoft.Research.Kinect.Nui; using Coding4Fun.Kinect.WinForm;
haar = new HaarCascade("haarcascade_frontalface_alt_tree.xml");
vai pupolar o objecto haar com o ficheiro xml
kinect.Initialize(RuntimeOptions.UseColor); kinect.VideoFrameReady += new EventHandler(kinect_VideoFrameReady); kinect.VideoStream.Open(ImageStreamType.Video, 2, ImageResolution.Resolution640x480, ImageType.Color);
public Form1() { InitializeComponent(); haar = new HaarCascade("haarcascade_frontalface_alt_tree.xml"); kinect.Initialize(RuntimeOptions.UseColor); kinect.VideoFrameReady += new EventHandler(kinect_VideoFrameReady); kinect.VideoStream.Open(ImageStreamType.Video, 2, ImageResolution.Resolution640x480, ImageType.Color); }
Agora que ja temos o event hanler do VideoFrameReady, ele vai receber no ImageFreameReayEventArgs todos os dados relevantes acerca da imagem.
A primeira tarefa vai ser converter a imagem capturada num bitmap e converte-la outra vez para uma imagem do Emgu, de modo a podermos processa-la
Image kinImage = new Image(e.ImageFrame.ToBitmap());
Image grayframe = nextFrame.Convert();
grayframe.DetectHaarCascade( haar, 1.4, 4, HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(grayframe.Width / 8, grayframe.Height / 8) )[0];
foreach (var face in faces) { nextFrame.Draw(face.rect, new Bgr(0, double.MaxValue, 0), 3); }
imageBox1.Image = nextFrame;
void kinect_VideoFrameReady(object sender, ImageFrameReadyEventArgs e) { Image kinImage = new Image(e.ImageFrame.ToBitmap()); using (Image; nextFrame = kinImage) { if (nextFrame != null) { // there's only one channel (greyscale), hence the zero index Image grayframe = nextFrame.Convert(); var faces = grayframe.DetectHaarCascade( haar, 1.4, 4, HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(grayframe.Width / 14, grayframe.Height / 14) )[0]; foreach (var face in faces) { nextFrame.Draw(face.rect, new Bgr(0, double.MaxValue, 0), 3); } imageBox1.Image = nextFrame; } } }
Em excelentes condições de luminusidade a detecção de faces funciona na perfeição