What I'm hacking now?

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.