jueves, 26 de abril de 2012

Practica #3

Aqui les muestro de como termino el programa en un video espero que les guste

Introducción

Usaremos las redes neuronales para detectar patrones en los datos.
en la practica 3 se a decidido utilizar las red neuronal para el reconocimiento de rostros de las personas. la aplicación fue inspirada por los últimos avances en los programas de las cámaras digitales, el programa es capturar tus características faciales  para luego crear una representación estática de su rostro.


Objetivo 


Que la cámara sin importar la posición de la personas o incluso si hay mas de una que el programa te reconozca y te pueda localizar.
Lograr lo anterior hay que entrenar al programa utilizando una gran variedad de fotos para que el programa te pueda reconocer los ojos, la boca, la nariz.



Justificación

Se decidió las redes neuronales por el gran uso que este se le puede dar en cualquier lugar como de seguridad de una empresa o uso policíaco, hasta en el uso de juegos.  La verdad el uso de redes neuronales tiene una gran espacio para abarcar y por lo que me llego a llamar la atención.

plactica 3 
En este  platica me presente con mucho retos, uno de estos retos fue entender el uso de las funciones de la librería del openCV, aunque esta librería es muy útil no pude encontrar bueno ejemplos o no los comprendí, porque se me dificultaba mucho y mas al usar una función.


El programa que realice usando esta librería tenia que reconocer los patrones de unas fotos que le indicara para luego mostrarte cuales son las caras de la foto.
en el dia una realice una investigación de como hacer este programa buscan por Internet en una variedad de pag.
En el día dos y tres empece a realizar el programa en cuestión con la información que encontré sobre la librería.
En el día cuatro, cinco, seis y siete fue a corregir los errores del programa, uno de los errores fueron que llamaba a funciones antes de tiempo por lo que cual me generaba un errores,  otro error fue que aparte de llamar a las funciones tenia que definir ciertas características a las funciones para que no hubiera ningún error. Otro problema que tuve fue que no me quiere ejecutar el programa aunque si me compila, por lo cual ya no se que hacer con el código.

El reconocimiento de rostro el programa a continuacion fue realizado en visual Stdio2010el codigo es el siguiente:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace MultiFaceRec
{
    static class Program
    {
        /// <summary>
        /// Punto de entrada principal para la aplicación.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FrmPrincipal());
        }
    }
}
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.CV.CvEnum;
using System.IO;
using System.Diagnostics;

namespace MultiFaceRec
{
    public partial class FrmPrincipal : Form
    {
        //Declararation of all variables, vectors and haarcascades
        Image<Bgr, Byte> currentFrame;
        Capture grabber;
        HaarCascade face;
        HaarCascade eye;
        MCvFont font = new MCvFont(FONT.CV_FONT_HERSHEY_TRIPLEX, 0.5d, 0.5d);
        Image<Gray, byte> result, TrainedFace = null;
        Image<Gray, byte> gray = null;
        List<Image<Gray, byte>> trainingImages = new List<Image<Gray, byte>>();
        List<string> labels= new List<string>();
        List<string> NamePersons = new List<string>();
        int ContTrain, NumLabels, t;
        string name, names = null;


        public FrmPrincipal()
        {
            InitializeComponent();
            //Load haarcascades for face detection
            face = new HaarCascade("haarcascade_frontalface_default.xml");
            //eye = new HaarCascade("haarcascade_eye.xml");
            try
            {
                //Load of previus trainned faces and labels for each image
                string Labelsinfo = File.ReadAllText(Application.StartupPath + "/TrainedFaces/TrainedLabels.txt");
                string[] Labels = Labelsinfo.Split('%');
                NumLabels = Convert.ToInt16(Labels[0]);
                ContTrain = NumLabels;
                string LoadFaces;

                for (int tf = 1; tf < NumLabels+1; tf++)
                {
                    LoadFaces = "face" + tf + ".bmp";
                    trainingImages.Add(new Image<Gray, byte>(Application.StartupPath + "/TrainedFaces/" + LoadFaces));
                    labels.Add(Labels[tf]);
                }
            
            }
            catch(Exception e)
            {
                //MessageBox.Show(e.ToString());
                MessageBox.Show("Nothing in binary database, please add at least a face(Simply train the prototype with the Add Face Button).", "Triained faces load", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

        }


        private void button1_Click(object sender, EventArgs e)
        {
            //Initialize the capture device
            grabber = new Capture();
            grabber.QueryFrame();
            //Initialize the FrameGraber event
            Application.Idle += new EventHandler(FrameGrabber);
            button1.Enabled = false;
        }


        private void button2_Click(object sender, System.EventArgs e)
        {
            try
            {
                //Trained face counter
                ContTrain = ContTrain + 1;

                //Get a gray frame from capture device
                gray = grabber.QueryGrayFrame().Resize(320, 240, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);

                //Face Detector
                MCvAvgComp[][] facesDetected = gray.DetectHaarCascade(
                face,
                1.2,
                10,
                Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,
                new Size(20, 20));

                //Action for each element detected
                foreach (MCvAvgComp f in facesDetected[0])
                {
                    TrainedFace = currentFrame.Copy(f.rect).Convert<Gray, byte>();
                    break;
                }

                //resize face detected image for force to compare the same size with the 
                //test image with cubic interpolation type method
                TrainedFace = result.Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
                trainingImages.Add(TrainedFace);
                labels.Add(textBox1.Text);

                //Show face added in gray scale
                imageBox1.Image = TrainedFace;

                //Write the number of triained faces in a file text for further load
                File.WriteAllText(Application.StartupPath + "/TrainedFaces/TrainedLabels.txt", trainingImages.ToArray().Length.ToString() + "%");

                //Write the labels of triained faces in a file text for further load
                for (int i = 1; i < trainingImages.ToArray().Length + 1; i++)
                {
                    trainingImages.ToArray()[i - 1].Save(Application.StartupPath + "/TrainedFaces/face" + i + ".bmp");
                    File.AppendAllText(Application.StartupPath + "/TrainedFaces/TrainedLabels.txt", labels.ToArray()[i - 1] + "%");
                }

                MessageBox.Show(textBox1.Text + "´s face detected and added :)", "Training OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch
            {
                MessageBox.Show("Enable the face detection first", "Training Fail", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }


        void FrameGrabber(object sender, EventArgs e)
        {
            label3.Text = "0";
            //label4.Text = "";
            NamePersons.Add("");


            //Get the current frame form capture device
            currentFrame = grabber.QueryFrame().Resize(320, 240, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);

                    //Convert it to Grayscale
                    gray = currentFrame.Convert<Gray, Byte>();

                    //Face Detector
                    MCvAvgComp[][] facesDetected = gray.DetectHaarCascade(
                  face,
                  1.2,
                  10,
                  Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,
                  new Size(20, 20));

                    //Action for each element detected
                    foreach (MCvAvgComp f in facesDetected[0])
                    {
                        t = t + 1;
                        result = currentFrame.Copy(f.rect).Convert<Gray, byte>().Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
                        //draw the face detected in the 0th (gray) channel with blue color
                        currentFrame.Draw(f.rect, new Bgr(Color.Red), 2);


                        if (trainingImages.ToArray().Length != 0)
                        {
                            //TermCriteria for face recognition with numbers of trained images like maxIteration
                        MCvTermCriteria termCrit = new MCvTermCriteria(ContTrain, 0.001);

                        //Eigen face recognizer
                        EigenObjectRecognizer recognizer = new EigenObjectRecognizer(
                           trainingImages.ToArray(),
                           labels.ToArray(),
                           3000,
                           ref termCrit);

                        name = recognizer.Recognize(result);

                            //Draw the label for each face detected and recognized
                        currentFrame.Draw(name, ref font, new Point(f.rect.X - 2, f.rect.Y - 2), new Bgr(Color.LightGreen));

                        }

                            NamePersons[t-1] = name;
                            NamePersons.Add("");


                        //Set the number of faces detected on the scene
                        label3.Text = facesDetected[0].Length.ToString();
                       
                        /*
                        //Set the region of interest on the faces
                        
                        gray.ROI = f.rect;
                        MCvAvgComp[][] eyesDetected = gray.DetectHaarCascade(
                           eye,
                           1.1,
                           10,
                           Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,
                           new Size(20, 20));
                        gray.ROI = Rectangle.Empty;

                        foreach (MCvAvgComp ey in eyesDetected[0])
                        {
                            Rectangle eyeRect = ey.rect;
                            eyeRect.Offset(f.rect.X, f.rect.Y);
                            currentFrame.Draw(eyeRect, new Bgr(Color.Blue), 2);
                        }
                         */

                    }
                        t = 0;

                        //Names concatenation of persons recognized
                    for (int nnn = 0; nnn < facesDetected[0].Length; nnn++)
                    {
                        names = names + NamePersons[nnn] + ", ";
                    }
                    //Show the faces procesed and recognized
                    imageBoxFrameGrabber.Image = currentFrame;
                    label4.Text = names;
                    names = "";
                    //Clear the list(vector) of names
                    NamePersons.Clear();

                }

        private void label5_Click(object sender, EventArgs e)
        {

        }

        private void imageBoxFrameGrabber_Click(object sender, EventArgs e)
        {

        }

    }
}

Aquí les dejo el vídeo

file:///C:/Users/luis/Documents/Camtasia%20Studio/camara/camara.html


Código

#include <stdio.h> 
#include "cv.h" 
#include "highgui.h" 


void displayDetections(IplImage * pInpImg, CvSeq * pFaceRectSeq); 

int main(int argc, char** argv) 
{ 
     
     IplImage * pInpImg = 0; 
     CvHaarClassifierCascade * pCascade = 0;  
     CvMemStorage * pStorage = 0;       
     CvSeq * pFaceRectSeq;               

 
     if(argc < 2) 
     { 
         printf("Missing name of image file!\n" 
                "Usage: %s <imagefilename>\n", argv[0]); 
         exit(-1); 
     } 

     pInpImg = (argc > 1) ? cvLoadImage(argv[1], CV_LOAD_IMAGE_COLOR) : 
0; 
     pStorage = cvCreateMemStorage(0); 
     pCascade = (CvHaarClassifierCascade *)cvLoad 
        
("deepti/eclipseopencv/detectface/src/haarcascade_frontalface_default.xm\ 
l", 
        0, 0, 0 ); 

     if( !pInpImg || !pStorage || !pCascade ) 
     { 
         printf("Initialization failed: %s\n", 
             (!pInpImg)?  "can't load image file" : 
             (!pCascade)? "can't load haar-cascade -- " 
                          "make sure path is correct" : 
             "unable to allocate memory for data storage", argv[1]); 
         exit(-1); 
     } 

     // detect faces in image 
     pFaceRectSeq = cvHaarDetectObjects 
         (pInpImg, pCascade, pStorage, 
         1.1,                       // increase search scale by 10% each 
pass;
         3,                         // merge groups of three detections 
         CV_HAAR_DO_CANNY_PRUNING,  // skip regions unlikely to contain a 
face 
         cvSize(40,40),cvSize(0,0));            // smallest size face to 
detect = 40x40 


     // display detected faces 
     displayDetections(pInpImg, pFaceRectSeq); 

     // clean up and release resources 
     cvReleaseImage(&pInpImg); 
     if(pCascade) cvReleaseHaarClassifierCascade(&pCascade); 
     if(pStorage) cvReleaseMemStorage(&pStorage); 

     return 0; 
} 


void displayDetections(IplImage * pInpImg, CvSeq * pFaceRectSeq) 
{ 
     const char * DISPLAY_WINDOW = "Haar Window"; 
     int i; 

     // create a window to display detected faces 
     cvNamedWindow(DISPLAY_WINDOW, CV_WINDOW_AUTOSIZE); 

     // draw a rectangular outline around each detection 
     for(i=0;i<(pFaceRectSeq? pFaceRectSeq->total:0); i++ ) 
     { 
         CvRect* r = (CvRect*)cvGetSeqElem(pFaceRectSeq, i); 
         CvPoint pt1 = { r->x, r->y }; 
         CvPoint pt2 = { r->x + r->width, r->y + r->height }; 
         cvRectangle(pInpImg, pt1, pt2, CV_RGB(0,255,0), 3, 4, 0); 
     } 

     // display face detections 
     cvShowImage(DISPLAY_WINDOW, pInpImg); 
     cvWaitKey(0); 
     cvDestroyWindow(DISPLAY_WINDOW); 
}

Código de ejemplo del open CV en C

Aun se esta investigando librerías, y lo que hemos logrado es saber usar algunos ejemplo de la libreria que deseamos realizar.


#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <highgui.h>
using namespace std;

int main(int argc, char *argv[])
{
 
    IplImage  *img = cvLoadImage( "mty.jpg",1 );

    cvNamedWindow("ventana", CV_WINDOW_AUTOSIZE );

    cvShowImage("ventana", img );
    printf("\nUPIITA");
    cvWaitKey(0);

    cvReleaseImage( &img );

    cvDestroyWindow("ventana");


    
    system("PAUSE");
    return EXIT_SUCCESS;
}