What I'm hacking now?

11 de abril de 2009

Contour Retrival and DrawContours

Filed under: OpenCV — pirunga @ 5:55 pm
Tags: , , , , ,

This post will explain how to use  the function cvFindContours and cvDrawContours

Este post irá explicar como usar as funções cvFindContours e cvDrawContours

good study =)

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

int main( int argc, char** argv )
{
    IplImage* src;
    if( src=cvLoadImage("pic1.png", 0) )
    {
        IplImage* dst = cvCreateImage( cvGetSize(src), 8, 3 );
        CvMemStorage* storage = cvCreateMemStorage(0);
        /* Create a Storage (it's a stack) , this is a low-level structure used
        to store dynamicaly growing data structures in our case sequences ( CvSeq )
        The parameter of cvCreateMemStorage is the block_size (size of the storage
        block in bytes). If zero size is set to default value 64K.
           Cria uma pilha, CvMemStorage é uma estrutura de baixo nível usada para
        alocar dinamicamente estruturas de dados que podem crescer, no nosso caso
        sequências ( CvSeq ). O parametro da função cvCreateMemStorage é o tamanho
        do bloco em bytes, se 0 será setado o valor padrão de 64K
        */
        CvSeq* contour = 0;
        /* Declare a CvSeq pointer */
        /* Declara o ponteiro para uma CvSeq */
        CvFont dfont;
        /*
        Declare a CvFont structure, this is used to draw text in OpenCV
        Declara uma estrutura CvFont, é utilizado para desenhar texto no Opencv
        */
        float hscale      = 0.5f;
        float vscale      = 0.5f;
        float italicscale = 0.0f;
        int  thickness    = 1;
        /* Values that would be used in CvFont:
                  hscale = horizontal scale
                  vscale = vertical scale
                  italicscale = italic scale
                  thickness = thickness (? I don't know how to explain this better
           Valores que serão utilizados pela CvFont:
                   hscale = escala horizontal
                   vscale = escala vertical
                   italicscale = escala de itálico
                   thickness = grossura da linha desenhada
        */
        char texto[255]    = "";
        /* String buffer */
        /* Uma string */
        cvInitFont (&dfont, CV_FONT_HERSHEY_SIMPLEX , hscale, vscale, italicscale, thickness, CV_AA);
        /* this function Initialize the CvFont, first parameter is the pointer to the CvFont, second
        parameter is the style of the font you can use:
                  CV_FONT_HERSHEY_SIMPLEX - normal size sans-serif font
                  CV_FONT_HERSHEY_PLAIN - small size sans-serif font
                  CV_FONT_HERSHEY_DUPLEX - normal size sans-serif font (more complex than CV_FONT_HERSHEY_SIMPLEX)
                  CV_FONT_HERSHEY_COMPLEX - normal size serif font
                  CV_FONT_HERSHEY_TRIPLEX - normal size serif font (more complex than CV_FONT_HERSHEY_COMPLEX)
                  CV_FONT_HERSHEY_COMPLEX_SMALL - smaller version of CV_FONT_HERSHEY_COMPLEX
                  CV_FONT_HERSHEY_SCRIPT_SIMPLEX - hand-writing style font
                  CV_FONT_HERSHEY_SCRIPT_COMPLEX - more complex variant of CV_FONT_HERSHEY_SCRIPT_SIMPLEX
        third to sixth parameters are those that we defined above, last is the type of the line (look to
        my cvLine example)
          esta função inicializa a estrutura CvFont, primeiro parametro é um ponteiro para a CvFont,
        segundo parametro é o estilo da fonte que pode ser uma das mostradas acima, terceiro ao sexto
        são os parametros criados acima, ultimo parametro é o tipo da linha (olhe os exemplos de cvLine)
        */
        cvNamedWindow( "Source", 1 );
        cvShowImage( "Source", src );
        /* Create a window and display the source image in it */
        /* Cria uma janela e mostra a imagem src */
        cvNamedWindow( "Components", 1 );
        cvFindContours( src, storage, &contour, sizeof(CvContour), CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE  , cvPoint(0,0) );
        /* This function finds all contours in an image,
        First parameter: IplImage* source, must be 8bit single channel image, the image is treated as a binary image
        you can use cvThreshold, cvAdaptiveThreshold or Canny to get such binarized image. In my example I used a
        binary image
        Second parameter is a storage for the retrieved contours
        Third parameter is a pointer to the CvSeq*,
        Forth parameter: Size of the sequence header, >=sizeof(CvChain) if method=CV_CHAIN_CODE,
        and >=sizeof(CvContour) otherwise.
        5th parameter: its the retriaval mode:
            CV_RETR_EXTERNAL - retrive only the extreme outer contours
            CV_RETR_LIST - retrieve all the contours and puts them in the list
            CV_RETR_CCOMP - retrieve all the contours and organizes them into two-level hierarchy: top level are external
            boundaries of the components, second level are bounda boundaries of the holes
            CV_RETR_TREE - retrieve all the contours and reconstructs the full hierarchy of nested contours
        6th parameter: Approximation method (for all the modes, except CV_LINK_RUNS, which uses built-in approximation).
              CV_CHAIN_CODE - output contours in the Freeman chain code. All other methods output polygons (sequences of vertices).
              CV_CHAIN_APPROX_NONE - translate all the points from the chain code into points;
              CV_CHAIN_APPROX_SIMPLE - compress horizontal, vertical, and diagonal segments, that is, the function leaves only
              their ending points;
              CV_CHAIN_APPROX_TC89_L1,CV_CHAIN_APPROX_TC89_KCOS - apply one of the flavors of Teh-Chin chain approximation algorithm.
              CV_LINK_RUNS - use completely different contour retrieval algorithm via linking of horizontal segments of 1?s.
              Only CV_RETR_LIST retrieval mode can be used with this method.
        7th parameter: Offset, by which every contour point is shifted. This is useful if the contours are extracted from the image ROI
        and then they should be analyzed in the whole image context.

            Esta função acha todos os contornos em uma imagem.
        O primeiro parametro deve ser uma imagem de 8bits de um único canal, a imagem será tratada como uma imagem binária,
        você pode usar as funções cvThreshold, cvAdaptiveThreshold ou Canny para binarizar as imagens, no meu exemplo eu uso
        uma imagem binária logo de inicio.
        Segundo parametro: é a pilha para armazenamento dos contornos encontrados
        Terceiro parametro: u ponteiro para a CvSeq*
        4° parametro: tamenho do cabeçalho da sequencia, >=sizeof(CvChain) se o método for CV_CHAIN_CODE, senão sizeof(CvContour)
        5° parametro: é o modo como o contorno é retornado, podendo assumir os macros declarados acima,
        6° parametro é o método de aproximação (também declarado acima)
        7° Offset, é util caso seu contorno seja retirado de uma região de interesse, porém deve ser analizado no contexto completo da imagem.
            */

        cvZero( dst );
        /* This function cvZero put Zero on the CvMat* in this case I pass an IplImage that is based on an CvMat*
           Esta função imprime zeros dentro da CvMat* que é o argumento, no caso eu passo uma IplImage que é baseada
           em uma CvMat*
           */
        for( ; contour != 0; contour = contour->h_next )
        {
            /* for nothing, contour != 0, contour points to next contour */
            cvDrawContours( dst, contour, CV_RGB(0,0,255), CV_RGB(0,0,255), -1, 1, 8 ,cvPoint(0,0) );
            /* This Function draw contours in images
            first argument is the image where the contours will be drawn
            second is the contours (we get this with cvFindContours)
            third is the color of the external contour
            forth is the color of the hole defined by the contour
            5th is  the Maximal level for drawn contours. If 0, only contour is drawn.
                        If 1, the contour and all contours after it on the same level are drawn.
                        If 2, all contours after and all contours one level below the contours are drawn, etc
                        If the value is negative, the function does not draw the contours following after contour
                        but draws child contours of contour up to abs(max_level)-1 level
            6th is the line thickness, if negative the contour will be Filled;
            7th is line type
            8th is an offset to the draw
            */
            sprintf(texto, "Area: %g", cvContourArea( contour, CV_WHOLE_SEQ ));
            /* put the text between " " in the string texto,
            cvContourArea returns a double argument and is the Area inside the contour
            the value can be negative because this depends on the contour orientation
            first argument is the contour, second is the slice of the contour to be calculated
            CV_WHOLE_SEQ will use the hole sequence of the contour
            poe o texto entre "" na string texto,
            cvContourArea calcula a area definida pelo contorno, este valor pode ser negativo
            pois o valor depende da orientação do contorno.
            */

            cvPutText(dst, texto, cvPoint(15, 15), &dfont, CV_RGB(0, 255, 0));
            /* this function draw the text in the image,
            first parameter is the image to draw
            2nd is the string to be drawn
            3rd is the starting point to draw the text
            4th is the pointer to the CvFont (that defines how the font will be)
            last parameter is the color of the text.

            esta função desenha um texto na imagem
            primeiro argumento é a imagem em que o texto será desenhado, 2° é a string do
            texto, 3º é o ponto inicial para o desenho, 4° é um ponteiro para CvFont
            ultimo parametro é a cor do texto
            */
            sprintf(texto, "ArcLength: %g", cvArcLength( contour, CV_WHOLE_SEQ, -1 ));
            /* cvArcLength calculate the length of the contour
            first parameter is the contour, second is the slice (tarting and ending points
            of the curve, by default the whole curve length is calculated.)
            last parameter is: is_closed?
            >0 => is closed
            =0 => is unclosed
            <0 => look to the CV_SEQ_FLAG_CLOSED of the ((CvSeq*)curve)->flag
               Calcula o comprimento do contorno, primeiro parametro é o contorno, segundo é o
            "slice" primeiro e ultimo ponto da sequencia, por padrão calcula-se o comprimento da
            curva inteira; ultimo parametro diz se a curva é fechada ou não: 0 (não é fechada),
            >0 (é fechada), <0 ( olha na estrutura do CvSeq por uma flag 

            */
            cvPutText(dst, texto, cvPoint(15, 30), &dfont, CV_RGB(0, 255, 0));

            cvShowImage( "Components", dst );

            cvSaveImage("aaa.jpg", dst);

            cvWaitKey(0);
            /*Waits until a key is pressed */
            cvZero(dst);
        }

    }
    return 0;
}

Here I show my input image and some of the output images =)
cya ! to the next post

6 de abril de 2009

Desenhando com OpenCV (aula2)

Filed under: OpenCV — pirunga @ 10:35 pm
Tags: , , ,

Hoje vamos olhar algumas funções de desenho! =)
Today lets study some drawing functions =)
First just some lines , rectangles, circles and ellipses;
Apenas algumas linhas, retangulos, circulos e elipses inicialmente;

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

int main()
{
  int gap;
  CvPoint aux1,aux2;
  cvNamedWindow("Drawing", CV_WINDOW_AUTOSIZE);
  IplImage* cool;
  cool = cvCreateImage(cvSize(300,300), IPL_DEPTH_8U, 3);
  /* creating an image with size 300x300, unsigned 8-bit integers, 3-channels RGB */
  /* criando uma imagem 300x300, 8 bits inteiros sem sinal, 3 canais RGB */

  cvLine( cool, cvPoint(0,0), cvPoint(300,300), CV_RGB(0,255,0), 1,CV_AA, 0 );
  cvLine( cool, cvPoint(300,0), cvPoint(0,300), CV_RGB(0,255,0), 1,CV_AA, 0 );
  /* first argument obviously is the pointer to the IplImage; 2nd is the first point
     of the line; CvPoint function returns a Point that opencv can work with; 3rd is
     the ending point; 4th is the color of the line, you may use the CV_RGB macro;
     5th argument is the line thickness; 6th argument is the line type, it can be
     4 to 4-connected line, 8 for 8-connected line, CV_AA to antialiased line; last
     argument is number of fractional bits in the point coordinates.
     primeiro argumento é o ponteiro para a IplImage; 2° é o primeiro ponto da linha
     3° é o ultimo ponto da linha; CvPoint é uma função que transforma as cordenadas
     dadas em uma estrutura que o OpenCV pode trabalhar; o 4° argumento é a cor; deve-
     se utilizar o macro CV_RGB; 5° é a grossura da linha; 6° é o tipo da linha, pode
     assumir os valores 4, 8 ou CV_AA, 4 (4-connected line), 8 (8-connected line) e
     CV_AA para anti aliased line
  */

  for ( gap = 300; gap != 0; gap -= 30)
  {
    aux1 = cvPoint(cool->width - gap, cool->height - gap);
    /* here I am accessing some informations of the IplImage directly */
    /* aqui eu acessei algumas informações do IplImage diretamente    */
    aux2 = cvPoint(gap, gap);
    cvRectangle(  cool, aux1, aux2, CV_RGB(255,0,0), 1, CV_AA, 0 );
    /* The arguments are the same as cvLine, only 2nd and 3rd have different
       interpretations, 2nd is one of the rectangle vertices and 3rd is the
       opposite vertice.
       Os argumentos são iguais ao do cvLine, apenas o 2° e 3° são diferentes
       2° é um dos vértices, e o 3° é o vértice oposto
    */
  }
  cvCircle( cool, cvPoint(150,150), 90, CV_RGB(0,0,255), 1, CV_AA, 0 );
  /* first argument is the pointer to IplImage, second is the center of the circle
     3rd is the radius, 4th is the color, 5th is thickness (if <0 it will be filled),
     6 is the linetype, last is the shift (number of fractional bits in the point
     coordinates).
     Primeiro argumento é o ponteiro para uma estrutura IplImage, segundo é o centro
     do circulo, terceiro é o raio, 4° é a cor, os tres ultimos são iguais ao cvLine
  */
  cvEllipse( cool, cvPoint(150,150), cvSize(90,120), 0, 0, 360, CV_RGB(0,255,0), 1, CV_AA,0 );
  cvEllipse( cool, cvPoint(150,150), cvSize(90,120), 90, 0, 360, CV_RGB(0,255,0), 1, CV_AA,0 );
  cvEllipse( cool, cvPoint(150,150), cvSize(90,120), 45, 0, 360, CV_RGB(0,255,0), 1, CV_AA,0 );
  cvEllipse( cool, cvPoint(150,150), cvSize(90,120), 145, 0, 360, CV_RGB(0,255,0), 1, CV_AA,0 );
  /* This function cvEllipse draw an ellipse, 1st argument is pointer to IplImage, 2nd is the center
  of the ellipse, 3rd is the size of the ellipse's axis, 4th is the angle of the elipse, 5th
  is the initial angle of the elipse, 6th is the ending angle, 7th is the color, 8th is the tickness
  (if it is <0 ellipse will be filled), last two arguments are the same as in cvLine.
     Desenha uma elipse, primeiro argumento é o ponteiro para a imagem, 2° é o centro da elipse,
  3° é o tamanho dos eixos da elipse, 4° angulo da elipse, 5° angulo inicial da elipse, 6° angulo final
  ,7° cor, ultimos 3 parametros igual ao do cvCircle
  */

  cvShowImage("Drawing",cool);
  cvSaveImage( "output.jpg", cool );

  cvWaitKey(0);
  cvDestroyWindow("Drawing");
  cvReleaseImage(&cool);

  return 0;
}

Resultado:

Output.jpg

Output.jpg

Introdução OpenCV

Filed under: OpenCV — pirunga @ 2:31 am
Tags: , ,

OpenCV é uma biblioteca de processamento de Imagens e Inteligência Artificial da Intel livre que utiliza licensa BSD, e eu vou mostrar algumas pequenas demonstrações com códigos exemplo e coisas assim. =) (Não se assuste com os tamanhos… é que os códigos estão MUITO comentados e em duas linguas diferentes )

Começando de leve:

Como exibir imagens:

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

int main()
{
  IplImage* image = 0;
  /* Create a Pointer to the IplImage Structure */
  /* Cria um ponteiro para a estrutura IplImage */
  image = cvLoadImage( "/home/file.jpg", CV_LOAD_IMAGE_COLOR );
  if (!image)
    return -1; /*this line checks if the image was successfully loaded */
  /* Load an image from a file, now your pointer really points
  to an image structure.
  This is some definitions of highgui,
  #define CV_LOAD_IMAGE_COLOR       1
  #define CV_LOAD_IMAGE_GRAYSCALE   0
  #define CV_LOAD_IMAGE_UNCHANGED  -1
  if 1,  the image will be allocated in a 3-channel image structure
  if 0,  the image will be allocated in a single channel image structure
  converting to a grayscale if the image is coloured
  if -1, the image will be allocated "as it is"
  highgui supports:
    * Windows bitmaps - BMP, DIB
    * JPEG files - JPEG, JPG, JPE
    * Portable Network Graphics - PNG
    * Portabele Image format - PBM, PGM, PPM
    * Sun rasters - SR, RAS
    * TIFF files - TIFF, TIF

  Abre um arquivo de imagem, agora seu ponteiro realmente aponta
  para uma estrutura de imagem.
  Algumas definições da biblioteca highgui,
  #define CV_LOAD_IMAGE_COLOR       1
  #define CV_LOAD_IMAGE_GRAYSCALE   0
  #define CV_LOAD_IMAGE_UNCHANGED  -1
  se 1, força ser uma imagem de 3 canais
  se 0, força ser uma imagem de 1 canal, se a imagem for colorida
  ela será convertida para uma imagem grayscale
  se -1, a imagem será criada com o numero de canais originais
  A bibioteca highgui suporta os formatos mostrados acima, antes
  de começar a explicação em português.
  */

  cvNamedWindow( "My Picture", CV_WINDOW_AUTOSIZE);
  /* This create a window | Isto cria uma janela */

  cvShowImage( "My Picture", image );
  /* Displays the image in the window "My Picture" */
  /* Mostra a imagem na janela "My Picture"        */

  cvWaitKey(0);
  /* Wait a key press */
  /* Espera até que uma tecla seja pressionada */
  cvDestroyWindow( "My Picture" );
  /* Destroy the Window */
  /* Destroi a janela   */

  cvReleaseImage( &image );
  /* Free Memory */
  /* Libera memória */
  return 0;
}

Vamos a um exemplo um pouco mais interessante, encontrando os cantos… corner detection =)

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

int main()
{
  IplImage* image;
  image = cvLoadImage("lena.jpg", CV_LOAD_IMAGE_COLOR );
  if (!image)
     return -1;
  int method=1;
  /* I will show three methods of finding corners */
  /* Mostrarei três métodos de encontrar os cantos*/
  printf("Digite o método:\n0-Laplaciano\n1-Sobel\n2-Canny\n");
  scanf("%d",&method);
  IplImage* workfile;
  IplImage* workfile2;
  IplImage* dst;
   CvSize size = cvGetSize(image);
  /* Allocate a CvSize, its a structure that have width and lenght, cvGetSize get the
  size of the original image, so our corner image will have the same width and height
  */
  workfile = cvCreateImage(size,IPL_DEPTH_8U,1);
  workfile2 = cvCreateImage(size,IPL_DEPTH_8U,1);
  dst = cvCreateImage(size,IPL_DEPTH_32F,1);
   /* This function cvCreate Images create and allocate the image, its arguments are
  in this order:
  size -> CvSize structure you can create images using cvSize(width,height)
  The second argument:
  IPL_DEPTH_8U - unsigned 8-bit integers
  IPL_DEPTH_8S - signed 8-bit integers
  IPL_DEPTH_16U - unsigned 16-bit integers
  IPL_DEPTH_16S - signed 16-bit integers
  IPL_DEPTH_32S - signed 32-bit integers
  IPL_DEPTH_32F - single precision floating-point numbers
  IPL_DEPTH_64F - double precision floating-point numbers
  The third argument is the number of channels, our image will be one single channel
  image
  */
  switch (method)
  {
    case 0:  cvCvtColor( image, workfile, CV_RGB2GRAY );
             cvLaplace( workfile, dst, 3 ); /* dst is IPL_DEPTH_32F, because cvLaplace
             only accepts 8u->16s, 8u->32f, 32f->32f */
             break;
    /* cvCvtColor is a function that convert an image from one color space to another
    Functions cvLaplace, cvSobel, cvCanny must receive images with same channel numbers
    This will calculate the laplacian of image and save it in workfile, the third
    argument is the aperture size, its the kernel that will be used to calculate,
    can be: 1, 3, 5 or 7 refer to:
    http://opencv.willowgarage.com/wiki/CvReference#cvSobel for more info
       Irá calcular o laplaciano da imagem e salvar em workfile, o terceiro argumento
    é o tamanho do kernel que será utilizado para calcular o laplaciano, olhe o link
    acima para mais informações
    */
    case 1: cvCvtColor( image, workfile, CV_RGB2GRAY );
            cvSobel( workfile, workfile2, 2, 0, 3 );
            cvSobel( workfile, workfile, 0, 2, 3 );
            cvAdd(workfile, workfile2, workfile, NULL);
            break;
    /* cvCvtColor is a function that convert an image from one color space to another
    This function cvSobel calculate the the first, second, third or mixed derivatives
    of an image the third argument is the x order, 4th is y order, 5th argument is the
    aperture size, refer to that site to more info about the kernels
    A função cvSobel calcula as derivadas de primeira, segunda, terceira ou mistas da
    imagem e as salva em workfile, 3° argumento é a ordem da derivada em x, 4° ordem
    da derivada em y, 5° é o tamanho do kernel, olhe o site acima para mais informações
    */
    case 2: cvCvtColor( image, workfile, CV_RGB2GRAY );
            cvCanny( workfile, workfile, 50,100, 3 );
            break;
    /* cvCvtColor is a function that convert an image from one color space to another
    I need to use this because the cvCanny only accepts single channel images for this
    algorithm, the 3rd argument is the first threshold, 4th is second threshold, and
    5th is the same aperture size as the other functions. I sugest to change 3rd and
    4th args to see the result.
       cvCvtColor faz a transformação de um espaço de cores para outro, esta função é
    necessaria porque cvCanny apenas aceita arquivos com um único canal, o 3° argumento
    é o primeiro threshold do algorítmo, 4° é o segundo threshold do algorítimo, o
    ultimo argumento é o tamanho do kernel utilizado, como nas outras funções
    */
  }
  cvNamedWindow( "Original", CV_WINDOW_AUTOSIZE);
  cvNamedWindow( "Corners", CV_WINDOW_AUTOSIZE);  

  cvShowImage("Original", image);
  if (method == 0)
     cvShowImage("Corners", dst);
  else
     cvShowImage("Corners", workfile);
  cvWaitKey(0); 

  cvDestroyAllWindows();
  /* Destroy all Windows */
  /* Destroy todas as janelas */

  if (method == 0)
    cvSaveImage( "output.jpg", dst );
  else
    cvSaveImage( "output.jpg", workfile );

  /* cvSaveImage save the image with the name inside "" */

  cvReleaseImage(&image);
  cvReleaseImage(&workfile);

  return 0;
}

Results Below

Original

Original

Laplacian Operator

Laplacian Operator

Sobel Operator

Sobel Operator

Canny Algorithm

Canny Algorithm

Tema: Rubric. Blog no WordPress.com.

Seguir

Obtenha todo post novo entregue na sua caixa de entrada.