tutorial opencv
DESCRIPTION
Este documento se inicia dentro del Trabajo Fin de Carrera de Raúl Igual, alumno de la E.U.Politécnica de Teruel, sobre algoritmos de seguimiento de objetos en tiempo real. Este Trabajo Finde Carrera ha sido financiado por la Fundación Universitaria Antonio Gargallo,(http://www.fantoniogargallo.org/).TRANSCRIPT
-
TutorialdeOpenCV
23/04/08
RalIgualCarlosMedrano
-
TableofcontenstLicencia................................................................................................................................................3Historiadeldocumento.........................................................................................................................3Instalacinycompilacin.....................................................................................................................4TiposdedatosenOpencv....................................................................................................................8LibreraOpencv....................................................................................................................................7Funcionesinteresantes........................................................................................................................14FuncionesarealizarconOpencv........................................................................................................15
Abririmgenes...............................................................................................................................15Guardarimgenes..........................................................................................................................16Accederaunpixel.........................................................................................................................19
Gestionardistintostiposdeimgenes................................................................................................25Formatosdeficheros......................................................................................................................25Tiposdeimgenes.........................................................................................................................28Tiposdedatosdeunpxel.............................................................................................................29
Transformacionesafines.....................................................................................................................30Traslacin.......................................................................................................................................30Escalado.........................................................................................................................................34Rotacin.........................................................................................................................................38
Binarizacindeimgenes...................................................................................................................43Operacionesconmatrices...................................................................................................................47
Inversindematrices.....................................................................................................................47Multiplicacindematrices.............................................................................................................48
BIBLIOGRAFA................................................................................................................................51GNUFreeDocumentationLicense....................................................................................................54
-
LicenciaCopyright(c)2007RalIgualCataln,CarlosMedranoSnchez.
Permissionisgrantedtocopy,distributeand/ormodifythisdocumentunderthetermsoftheGNUFree Documentation License, Version 1.2or any later versionpublished by the FreeSoftwareFoundation;withnoInvariantSections,noFrontCoverTexts,andnoBackCoverTexts.Acopyofthelicenseisincludedinthesectionentitled"GNUFreeDocumentationLicense".
HistoriadeldocumentoEstedocumento se inicia dentro del TrabajoFindeCarreradeRal Igual, alumnode la E.U.PolitcnicadeTeruel,sobrealgoritmosdeseguimientodeobjetosentiemporeal.EsteTrabajoFinde Carrera ha sido financiado por la Fundacin Universitaria Antonio Gargallo,(http://www.fantoniogargallo.org/).
Versininicial:RalIgual,
AadidodelaseccindeinstalacinydelasfuncionescvReleaseXX:CarlosMedrano
Formato:CarlosMedrano,29122007
Versinmodificada:RalIgual,22042008.Sehanaadidolassalidasdelosprogramasysehanefectuadoalgunaspequeasmodificacionesenalgunospuntos.
-
InstalacinycompilacinParainstalarla librera, loprimeroquedebemosdehaceresdescargarnosladelsitio:http://sourceforge.net/projects/opencvlibrary/
Siladescargamosconuntar.gz,habrquedescomprimirlacon$tarxvzfopencv1.0.0.tar.gz
Ennuestrocasoeslaversin1.0.0.Despusbajaremosaldirectorioopencv1.0.0$cdopencv1.0.0
DespusconsultaremoselficheroINSTALL,yseguiremoslasinstruccionesqueallseexpliquen. Segn este documento, hay que tener en cuenta que se necesitan tenerinstaladasunaslibreras(porejemplolibpng).Estosepuedehacerdesdeelgestordepaquetes de nuestro equipo. Por ejemplo, en kubuntu suele aparecer como Adept(PackageManager)enformagrfica,odesdelalneadecomandosconaptitudeoapt.Cuandonoshablendelibreraconficherosdedesarrollo(developmentfiles),habrqueinstalarlaslib,perotambinlaslibdev(poeejemplo,libpng12dev).Unavezhechoesto,lainstalacinserealizaconlasinstruccionesqueindicaelficheroINSTALL:
$./configure
$make
$sudomakeinstall
Conestoseinstalarennuestroequipo.Noobstante,paraqueencuentrelalibreraalcompilaresnecesarioindicarlelarutaadecuada.ParaellosepuedemodificarlavariabledeentornoLD_LIBRARY_PATH,queesunalistadedirectoriosseparadosporpuntoycoma.Estohayquehacerloencadasesinobienennuestrofichero.bash_profiledenuestrodicrectorio/home/usuario/.OtraformamscmodaesaadirlarutadelalibreraOpenCV al fichero de configuracin /etc/ld.so.conf. En nuestro caso, la librera esten/usr/local/libporloqueelarchivoqueda
$more/etc/ld.so.conf
/usr/lib/atlas
/usr/local/lib/
-
traslocualbastahacer
$sudoldconfigv
paraqueencuentrelalibreraalcompilar.
Pero, cmocompilar un programa que usa la librera? Veamos un ejemplo con elsiguienteprograma,quecargarlaimagenlena.jpg,lomostrarenunaventana,yluegolo guardar en saliendo.jpg. Debe tener la imagen en el directorio de trabajo (aldescomprimiropencvesaimagenseencuentratambinenalgunaruta).
#include"cv.h"
#include"highgui.h"
#include
charname0[]="lena.jpg";//sedefineelficheroacargar
intmain()
{
IplImage*imagen=NULL;//inicializoimagen
imagen=cvLoadImage(name0,1);//cargamoslaimagen,
//secargaentrescolores
cvNamedWindow("test",1);//creamoslaventanadenombre"test"
//indicndoleconel1queajuste
//sutamaoaldelaimagen
cvShowImage("test",imagen);//representamoslaimagenenlaventana
cvSaveImage("saliendo.jpg",imagen);//guardamoslaimagen
cvWaitKey(0);//sepulsateclaparaterminar
cvDestroyAllWindows();//destruimostodaslasventanas
cvReleaseImage(&imagen);
return0;
}
Suponiendoqueesteprogramasellamaload_save.c,sepuedecompilarcon:
$ gcc load_save.c o load_save I/usr/local/include/opencv/L/usr/local/liblcvlhighgui
-
EsrecomendablehacerunMakefile,quepodraseras:
INC=/usr/local/include/opencv/
LIB=/usr/local/lib
all:load_save
load_save:load_save.c
gccWallload_save.coload_saveI$(INC)L$(LIB)lcvlhighgui
clean:
rmload_save
LaopcinWallengccdagrancantidaddeinformacin.Aunqueespesada,convienetenerlaavecespuesnosindicaposiblesfallosenelprograma.Conesteficherobastahacer:
$make
omakeallcadavezquequeramoscompilar.
-
LibreraOpencv
Las siglas Opencv provienen de los trminos anglosajones Open Source
Computer Vision Library. Por lo tanto, Opencv es una librera de tratamiento de
imgenes,destinadaprincipalmenteaaplicacionesdevisinporcomputadorentiempo
real.
Conesteinformesepretendeproveerdeladescripcindealgunasfuncionesde
inters, as comoexponer ejemploscompletosy compilablesdesuuso, yaqueesto
facilitar en gran medida su posterior aplicacin. Tambin es necesario definir los
principalestiposdedatosqueutilizaOpencv,yqueestninvolucradosconelempleode
lasfunciones,lamayoradeestostiposdedatossonestructurasdinmicas.
AlgunosapuntessobreOpencv
Es importante no confundir las funciones, con los tipos de datos propios de
Opencv.Paraello,lapropialibrerautilizaunasintaxisdistintaparacadacaso,conligeras
diferencias, aunqueenprincipiosi nosepresta ladebidaatencin, es fcil confundir
ambassintaxis.
CadaunadelasfuncionesreferenciadasenOpencvcomienzaconlassiglascv,
seguidadelnombredelafuncin,conlaprimeraletradecadaunadelaspalabrasque
componen dicho nombre en mayscula. Por ejemplo: cvCreateImage, cvInvert,
cvMatMulAdd...
Parareferirnosalostiposdedatoslasintaxisesmuysimilaraladelasfunciones,
aunqueconlanicadiferenciadequelostiposcomienzanconlasiglasCv.Porejemplo:
CvScalar, CvMat... No obstante existen algunos tipos que se declaran de forma
totalmentedistinta(IplImage...).Paraconcretarestasindicacionespasamosaexponerlos
principalestiposdedatos.
-
TiposdedatosenOpencv
Opencvproporcionaunostiposdedatosbsicosparasuutilizacin.Tambinnos
proveedetiposdedatosintroducidoscomoayudaal programador,parahacerqueel
accesoainformacindeintersseamssimple.Comenzamosladescripcindelostipos
dedatos:
CvArr
Esmuyimportantecomprenderqueestenoesuntipodedatosreal,sinoloquese
denominaunmetatype,esdecir,untipodedatoficticioqueseutilizadeformagenrica
alahoradedescribirlosparmetrosdelasfunciones.LanomenclaturaCvArr*seutiliza
sloparaindicarquela funcinaceptaarraysdemsdeuntipo,comopuedenser
IplImage*CvMat*oinclusoCvSeq*.
IplImage
El tipo de datos bsico en Opencv es el IplImage. Con este tipo de datos se
representanlasimgenesseandeltipoquesean:BGR,intensidad...
Pasamosamostrarlaordenacinyloscamposdeestaestructura:
typedefstruct_IplImage{
intnSize;/*tamaodelaestructuraiplImage*/
intID;/*versindelacabeceradelaimagen*/
intnChannels;
intalphaChannel;
intdepth;/*profundadaddelaimagenenpxeles*/
charcolorModel[4];
charchannelSeq[4];
intdataOrder;
intorigin;
intalign;/*alineamientode4o8byte*/
intwidth;
-
intheight;
struct_IplROI*roi;/*punteroalaROIsiexiste*/
struct_IplImage*maskROI;/*punteroalamxcaraROIsiexiste*/
void*imageId;/*usodelaaplicain*/
struct_IplTileInfo*tileInfo;/*containsinformationontiling
intimageSize;/*tamaotilenbytes*/
char*imageData;/*punteroalaimagenalineada*/
intwidthStep;/*tamaodealineamientodelineaenbytes*/
intBorderMode[4];/*thetop,bottom,left,andrightbordermode
*/
intBorderConst[4];/*constantsforthetop,bottom,left,and
rightborder*/
char*imageDataOrigin;/*punteroalaimagencompleta,sinalinear
*/
}IplImage;
Vamosadescribirmsenprofundidadaquelloscamposquenosvanasertilesen
nuestraaplicacin.
Los campos width y height contienen la anchura y la altura de la imagen
expresadasenpxeles.
El campodepthcontiene informacinsobreel tipodevalorde lospxeles. Los
posiblesvaloresdelcampodepthsonlossiguientes:
IPL_DEPTH_8U:Enterossinsignode8bits(unsignedchar)
IPL_DEPTH_8S:Enterosconsignode8bits(signedcharosimplementechar)
IPL_DEPTH_16S:Enterosde16bitsconsigno(shortint)
IPL_DEPTH_32S:Enterosconsignode32bits(int)
IPL_DEPTH_32F:Nmerosenpuntoflotanteconprecisinsimplede32bits(float)
El camponChannels indica el nmerode canales de color de la imagen. Las
imgenesenescaladegrisestienenunslocanal,mientrasquelasdecolortienen3o4
canales.
-
El campo widthStep contiene el nmero de bytes entre puntos de la misma
columnayfilassucesivas.Paracalcularladistanciaconwidthnoessuficiente,yaque
cadacolumnapuedeestaralineadaconunciertonmerodebytesparaobtenermayores
velocidadesdeprocesamiento.
ElcampoimageDatacontieneunpunteroalaprimeracolumnadelosdatosdela
imagen.
Es posible seleccionar algunas partes rectangulares de la imagen, lo que se
conocecomoregionesdeinters(ROI).LaestructuraIplImagecontieneelcamporoi,que
sinoesnulo(NULL),apuntaalaestructuraIplROI,quecontieneparmetrosdelaregin
seleccionada.
CvMat
UnadelasestructurasmsempleadasparaoperarconlasimgenesesCvMat,
quesedefinedelsiguientemodo:
typedefstructCvMat
{
introws;//nmerodefilas
intcols;//nmerodecolumnas
CvMatTypetype;//tipodematriz
intstep;//noseutiliza
union
{
float*fl;//punteroalosdatosdetipofloat
double*db;//punteroadatosdedobleprecisin
}data;
}CvMat
Secaracterizaporqueapartedealmacenarloselementoscomocualquiermatriz,
ofrecelaposibilidaddeaccederainformacinadicionalquepuederesultardeutilidad.En
losprogramasquerealicemosestetipodedatossiempreirnasociadosconlafuncin
-
cvCreateMatquenospermitirconfigurarlaestructuramatricialdemaneramuysencilla.
Estafuncinseencargadecrearal encabezadodela imagenydeubicarsusdatos.
Exponemossuestructura:
CvMat*cvCreateMat(introws,intcols,inttype);
rows:nmerodefilasdelamatriz
cols:nmerodecolumnasdelamatriz
type:tipodeloselementosdelasmatrices.Seespecificadela
forma:
CV_(S|U|F)C.Siendo:
bit_depth:profundidaddebit(8,16,31...)
numberofchannels:elnmerodecanalesdelamatriz
(S|U|F):eltipodedatosdebit:
S:consigno
U:sinsigno
F:flotante
Porejemplo.:
CV_8UC1significaquesetieneunamatrizdeuncanalde8bitdetipounsigned.
CV_32SC2equivaleaunamatrizdedoscanalesde32bitsigned.
CvScalar
LaestructuraCvScalaressimplementeunvectordecuatroelementos,peroque
resultamuytilalahoradeaccederalospxelesdeunaimagen,sobretodosiesde
color.LaestructuraCvScalareslasiguiente:
CvScalar
doubleval[4];//vector4D
Para acceder al campodeestaestructurabastaconadjuntar el nombrede la
mismaalapalabraval,conunpuntoentreambas,esdecir:
CvScalars;//definicindelavariablesdetipoCvScalar
s.val[0]=2;//inicializamoselprimerelementodesconelvalor
arbitrario2
-
Normalmente esta estructura suele ir acompaada de la funcincvScalar, que
permitedefinirtodoslosparmetrosdeunasolavez.Analizamoslafuncin:
inlineCvScalarcvScalar(doubleval0,doubleval1,doubleval2,
doubleval3=0);
donde:val0,val1...sonlosvaloresquetomanloselementosdela
estructura.
Vemosunejemplo:
CvScalars=cvScalar(1.0,3,4.6,5);
CvPointyCvPoint2D32f
LostiposdedatosCvPointyCvPoint2D32f,definenlascoordenadasdeunpunto,
elprimerodeellosconnmerosenterosyelsegundoconnmerosenpuntoflotante.
DescribimosenprimerlugarCvPoint:
typedefstructCvPoint
{
intx;/*coordenadax*/
inty;/*coordenaday*/
}
CvPoint;
DeformaanlogatenemoslaestructuraCvPoint2D32f:
typedefstructCvPoint2D32f
{
floatx;/*coordenadax*/
floaty;/*coordenaday*/
}
CvPoint2D32f;
Estas estructuras como algunas de las anteriores suelen ir acompaadas de
-
funcionesquefacilitansuusoydefinicin.EnestecasotenemoslasfuncionescvPointy
cvPoint2D32f,conlossiguientesparmetros:
inlineCvPointcvPoint(intx,inty);
inlineCvPoint2D32fcvPoint2D32f(doublex,doubley);
siendoxeylascoordenadasdelpunto.
Ejemplodeaplicacin:
CvPointpunto=cvPoint(100,200);
CvPoint2D32fpuntof=cvPoint2D32f(100.0,200.0);
CvSize
Estructurautilizadaparadefinirlasdimensionesdeunrectnguloenpxeles:
typedefstructCvSize
{
intwidth;/*anchuradelrectngulo(valorenpxeles)*/
intheight;/*alturadelrectngulo(valorenpxeles)*/
}
CvSize;
Estetiposeutilizasobretodoalahoradecrearimgenesnuevas,paradefinirsus
dimensiones.LafuncinasociadaaestetipoescvSize:
inlineCvSizecvSize(intwidth,intheight);//siendowidthyheight
lasdimensiones
Vemosunejemplodeaplicacin:
CvSizetamano=cvSize(100,200);
-
Funcionesinteresantes
Antesdeabordarloscasosdeintersseraconvenienteintroduciralgunasdelas
funcionesquemsseutilizarnenlosprogramassiguientes,yquesepuedenconsiderar
comunesatodoslostemasquetrataremos.
voidcvNamedWindow(charname,inttype);
Estafuncincreaunaventanagrfica.Analizamossusparmetros:
name:cadenadecaracteresquesirvecomonombredelaventana
type:formatodetamaodelaventana:
UtilizaremosCV_WINDOW_AUTOSIZE,osimplementepondremosun
1paraseleccionarestaopcin.
voidcvShowImage(charname,CvArr*img)
Estafuncindibujalaimagenindicadaenlaventanacorrespondiente.
Tienecomoparmetros:
name:nombredelaventanadondesedibujarlafuncin
img:imagenquedeseamosdibujar
voidcvDestroyAllWindows();
Estafuncineliminatodaslasventanasgrficasquehayansidocreadas
previamente.
voidcvReleaseImage(&CvArr*img);
Estafuncinseencargadeliberarelespaciodememoriaquehasido
asignadoaunaestructuraCvArr*.Poseeunnicoparmetro:
img:eselnombredelaimagenquesedesealiberar
voidcvmSet(CvMat*mat,introw,intcol,doublevalue)
Estafuncinguardaunelementoenunamatrizdeunsolocanalenpunto
flotante:
mat:Lamatrizdeentrada
row:Elndicedelafila
col:Elndicedelacolumna
value:Elnuevovalordelelementodelamatriz
-
voidcvmGet(constCvMat*mat,introw,intcol);
Retornaelvalorquetomaunelementodelamatrizindicada.
mat:matrizdeentrada,delacualseextraerelvalordeunode
suselementos
row:valordelndicedeseadoenlasfilas(ejevertical)
col:valordelndiceenlascolumnas(ejehorizontal).Juntocon
lafiladefinela posicindelelementodentrodelamatriz.
FuncionesarealizarconOpencv
Abririmgenes
ParaimplementarlaaccindeabririmgenesutilizandoOpencv,sehaceusodela
funcincvLoadImage.
Pasamos a describir los parmetros necesarios para poder trabajar con esta
funcin:
img=cvLoadImage(fileName,flag);
Siendo:
fileName:Nombredelficheroquesequierecargar
flag:Caractersticasdecargaenelfichero:
flag:>0:seobligaquelaimagencargadaseaunaimagendecolor
de3canales
flag=0:seobligaquelaimagencargadaseaunaimagenintensidad
de1canal
flag
-
deformasimilarafree().
Guardarimgenes
Se utiliza la funcin cvSaveImage para salvar las imgenes. Los parmetros
requeridos para su uso son muy parecidos a los empleados en la funcin anterior.
Pasamosadescribirloscamposdelafuncin:
cvSaveImage(outFileName,img)
Siendo:
outFileName:Nombredelficherodesalidaquedebercontenerala
imagenaguardar.
img:Imagenquesevaaguardar
Comoparticularidadcabedestacarquelaimagenquesesalvaescreadaporel
propioprogramayalmacenadaeneldirectoriodondeseencuentreelprograma.Porlo
tanto,noesnecesariodefinirningntipodeficherodealmacenamientoconantelacin.
Programadepruebadelasfunciones cvLoadImage y cvSaveImage
Para concretar los conceptos anteriormente expuestos vamos a mostrar dos
ejemplosclarosysencillosdelasfuncionescvLoadImageycvSaveImage.
Elprimerejemploeselsiguiente:
#include"cv.h"#include"highgui.h"#include
charname0[]="out10000.jpg";//sedefineelficheroacargar
intmain(){IplImage*imagen=NULL;//inicializoimagenimagen=cvLoadImage(name0,1);//cargamoslaimagen,//secargaentrescolorescvNamedWindow("test",1);//creamoslaventanadenombre
//"test"indicndoleconel1queajuste//sutamaoaldelaimagen
cvShowImage("test",imagen);//representamoslaimagenenlaventana
-
cvSaveImage("saliendo.jpg",imagen);//guardamoslaimagen
cvWaitKey(0);//sepulsateclaparaterminar
cvDestroyAllWindows();//destruimostodaslasventanascvReleaseImage(&imagen);return0;}
Alejecutarelprograma,semuestraenpantallaunaimagencomoladelafigura1
(laquesedeseacargar),quepermaneceenelmonitorhastaquesedetectalapulsacin
deunateclacualquiera.
Ademssegenerar unficheroenlarutaindicadaenlainstruccindeguardar
imagen,quecontendrestamismaimagen.
Enelprogramaanterior,elficheroimagensedefinedirectamenteenelcdigodel
mismo,asignandosunombreaunavariabledetipo char,queposteriormentesepasa
comoparmetroalafuncincvLoadImage,donderealmentesecargalaimagen.
Elsegundoejemplosediferencialigeramentedelanterior:
#include"cv.h"#include"highgui.h"#defineventana"Ventana1"#defineventana1"Ventana2"
intmain(intargc,char*argv[]){//Comprobamossihanpasadounaimagencomoparmetro,//sinopasamosunapordefectochar*filename=argc>=2?argv[1]:(char*)"lena.jpg";
Figura1
-
IplImage*imagen=NULL,*imagen1=NULL;
imagen=cvLoadImage(filename,1);//cargamoslaimagenenRGBimagen1=cvLoadImage(filename,0);//Cargamoslaimagen//enEscaladegrises
cvNamedWindow(ventana,0);//MostramoslaimagenenlaventanacvNamedWindow(ventana1,0);cvShowImage(ventana,imagen);cvShowImage(ventana1,imagen1);
cvWaitKey(0);
cvDestroyAllWindows();//destruimostodaslasventanascvReleaseImage(&imagen);cvReleaseImage(&imagen1);return0;}
Enestecdigoelnombredelficherosedebecargarporconsola,porlotantoesel
propiousuarioelquedecidequeimagencargarsinnecesidaddemodificaryrecompilarel
programa.Encasodequestenointroduzcaelnombredeningnficheroenlaconsola,
secargarelqueelpropioprogramaposeepordefecto:lena.jpg.
Portanto,sidesesemosabrir la imagenout4553.jpg,alahoradeejecutarel
programa,porconsoladeberamosescribir:./nombre_programarutadondeseubicala
imagenacargar.
Porejemplo,sielprogramasellamaloadsave.cypretendemoscargarlaimagenconruta
/home/raul/tpm2/out4553.jpg,escribimos:./loadsave/home/raul/tpm2/out4553.jpg.
Lasfigurassiguientesmuestranlamismaimagencargadaendosmodosdistintos:
encolor(figura4),yenescaladegrises(figura5).
Figura2 Figura3
-
Accederaunpixel
Comoessabido,elelementobsicodeunaimageneselpxel,portantoresulta
primordialsaberaccederaellos.
Opencvproporcionaunagranvariedaddemtodosparaaccedera lospxeles,
aquvamosadescribiralgunosdelosmsusados.
Mtodo1:Accesoindirectoalospxeles.
SebasaenlautilizacindelasfuncionescvGet2DycvSet2Dqueseencargande
encontrarelementosdeunarrayyconfigurarelementosdeunarrayrespectivamente.Las
describimosacontinuacin:
CvScalarcvGet2D(constCvArr*arr,intidx0,intidx1);
Siendo:
arr:arrayenelcualvamosabuscarelvalordelelementodeseado
idx0:ndicedefilasdelelemento
idy1:ndicedecolumnasdelelemento
LasalidadelafuncineselvalordelelementoyesdetipoCvScalar(unescalar).
voidcvSet2D(CvArr*arr,intidx0,intidx1,CvScalarvalue);
Siendo:
arr:arraydeentradaenelquevamosadefinirunodesuselementos
idx0:ndicedefilasdelelemento
Figura4 Figura5
-
idx1:ndicedecolumnasdelelemento
value:valorquedeseamosasignaralelemento(idx0,idx1)
Laestructuradedatosimplicadaenelaccesoalospxeleses CvScalar yest
definidaenlaslibrerasdeOpencv.
Pasamosamostrar el accesoa unpxel en unsistemamonocanal (imgenes
binariasoenescaladegrises):
IplImage*img=cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,1);
//Obtenemoselvalordeintensidadenunpxel
CvScalars;//definimoslaestructuradondealmacenaremoslosdatos
s=cvGet2D(img,i,j);//seobtieneelvalor(i,j)delpxel,que
quedaalmacenadoens.val[0]
printf("intensity=%f\n",s.val[0]);//imprimimosesevalor
//Fijamosunpxelaundeterminadoniveldeintensidad
s.val[0]=111;//asignamoselvalordeintensidaddeseado
cvSet2D(img,i,j,s);//configuramoselpxel(i,j)conesevalor
Enelcdigoanteriorsloseutilizaelcampos.val[0]delaestructuraCvScalar,ya
quealtenerunsoloniveldecolor,nicamenteesnecesariounindicador.
Enel casodetenerunsistemamulticanal(trescoloresparadefinirunpxel)el
accesoalospxelesserealizaconelsiguientecdigo:
IplImage*img=cvCreateImage(cvSize(640,480),IPL_DEPTH_32F,3);
//Obtenemoselvalordelpxel(i,j)deunaimagen
CvScalars;
s=cvGet2D(img,i,j);//obtenemoselvalorenelpxel(i,j)
printf("B=%f,G=%f,R=%f\n",s.val[0],s.val[1],s.val[2]);//
imprimimosesevalor
-
//Fijamosunpxelaunniveldecolordeterminado
s.val[0]=111;//Niveldeazul
s.val[1]=111;//Niveldeverde
s.val[2]=111;//Nivelderojo
cvSet2D(img,i,j,s);//asignamoslosnivelesanterioresalpxel
(i,j)
CabedestacarqueaquseutilizantrescamposdelaestructuraCvScalar,unopara
cadaniveldecolor(rojo,verdeyazul).
Podemosenunciaralgunadelascaractersticasdeestemtododeaccesoalos
pxeles.Comoaspectopositivocontienelaventajadequeeslaformamssencillade
accederaunpxel.Cmoinconvenientepodemoscitarqueespocoeficiente,ocomo
mnimo,menoseficientequelosotrosmtodos.
Mtodo2 :Utilizandopunterosalosdatosdelaimagen.
Paraello esnecesario acceder a lossiguientescamposde la estructura
IplImage*:height,width,widthstep,imageData.
Al ser una estructura puntero el acceso como sigue: nombre_variable >
nombre_del_campo
Paraunaimagenmonocanalcodificadaenbytes,utilizamoselsiguientecdigo:
IplImage*img=cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,1);
intheight=img>height;//obtenemoslaalturadelaimagenen
pxeles
intwidth=img>width;//anchuradelaimagenenpxeles
intstep=img>widthStep/sizeof(uchar);//calculamoselvalordel
paso
uchar*data=(uchar*)img>imageData;//cargamoslosdatosdela
imagenendata
data[i*step+j]=111;//fijamoselpixel(i,j)aundeterminado
valor
-
Paraunaimagenmulticanalcodificadaenbytes,deberemosescribir:
IplImage*img=cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,3);
intheight=img>height;//obtenemoslaalturadelaimagenen
pxeles
intwidth=img>width;//anchuradelaimagenenpxeles
intstep=img>widthStep/sizeof(uchar);//calculamoselvalordel
paso
intchannels=img>nChannels;//obtenemoselnmerodecanalesde
laimagen
uchar*data=(uchar*)img>imageData;//cargamoslosdatosdela
imagenendata
data[i*step+j*channels+k]=111;//fijamoselvalordeunodelos
canalesdelpixel(i,j)aun
determinadonivel,siendo:
// k=0paraelazul
// k=1paraelverde
// k=2paraelrojo
Comoventajasprincipalesdelaccesoalospxelesconpunterospodemoscitarque
esunsistemarelativamentesencillo(aunquemenosqueelanterior),ysobretodoesun
accesocontasasdeeficienciamuyelevadas.
Mtodo3:Accesodirecto
Estaesunade lasmejoresformasdeaccedera lospxeles,aunquesu
sintaxisesunpocomenosevidentequelasanteriores.
Para imgenesdeunsolo canal definimosel valor de un pxel a unacuanta
arbitraria,porejemplo111.
IplImage*img=cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,1);//imagen
de1canal
((uchar*)(img>imageData+i*img>widthStep))[j]=111;//accesoal
elementoi,j
-
Paraimgenesmulticanal:
IplImage*img=cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,3);//imagen
de3canales
((uchar*)(img>imageData+i*img>widthStep))[j*img>nChannels+
0]=111;//B
((uchar*)(img>imageData+i*img>widthStep))[j*img>nChannels+
1]=112;//G
((uchar*)(img>imageData+i*img>widthStep))[j*img>nChannels+
2]=113;//R
Seaccedeenelprimercasoalcolorazul,enelsegundoalverdeyenelterceroal
rojo.Lafilosofadelmtodoeslamismaqueenelmtodo2,peroenestaocasinde
formamscomprimidayeficiente.
Mtodo4:Utilizandolainformacindelasfilas
Sehaceusodeunafuncinauxiliarcomoenelcasoinicialparaelaccesoalos
datos,yunavezestncargadosseoperaconelloscomosidematricessetrataran.En
estaocasinutilizamoslafuncincvGetRawData:
uchar*data;
cvGetRawData(img,(uchar**)&data);
data[x*img>Width+y]=111;
-
Ejemplosdeaccesoapxeles
EnprimerlugarutilizamoselMtodo1(cvGet2D,cvSet2D)paraelaccesoalos
pxeles:
#include"cv.h"#include"highgui.h"#include
charname0[]="lena.jpg";inti=2,j=2;intmain(){IplImage*imagen=NULL;//seinicializaimagenimagen=cvLoadImage(name0,1);//secargalaimagen
CvScalars;//definimoselescalardondesealmacenar//elvalordelpxels=cvGet2D(imagen,i,j);//seobtieneelvalordelpxel(i,j)printf("B=%f,G=%f,R=%f\n",s.val[0],s.val[1],s.val[2]);//ens.val[0]quedaalmacenadoelprimer//color,ens.val[1]elsegundo...cvReleaseImage(&imagen);return0;}
Ahora vamos a utilizar un acceso ms eficiente mediante punteros. Para ello
aplicamoselmtodo3:
#include"cv.h"#include"highgui.h"#include
charname0[]="lena.jpg";inti=2,j=2;//elementoalqueacceder
intmain(){IplImage*imagen=NULL;//inicializoimagenints;
imagen=cvLoadImage(name0,1);//cargamoslaimagen
((uchar *)(imagen>imageData+i*imagen>widthStep))[j*imagen>nChannels+0]=111;//B ((uchar *)(imagen>imageData+i*imagen>widthStep))[j*imagen>nChannels+1]=112;//G ((uchar *)(imagen>imageData+i*imagen>widthStep))[j*imagen>nChannels
-
+2]=113;//R//paracomprobarsiefectivamenteelvalorhasidotomado,//leemoselcanalazuldelpxel s = ((uchar *)(imagen>imageData + i*imagen>widthStep))[j*imagen>nChannels+0];printf("B=%d\n",s);//imprimimoselresultado//(debeser111sifuncionacorrectamente);cvReleaseImage(&imagen);return0;}
Gestionardistintostiposdeimgenes
Una imagennoesmsqueunamatrizounarraybidemensional denmeros,
siendocadaceldaelequivalenteaunpxel.Lasimgenesposeendimensionesdeancho
xalto(widthxheight),siendoelancholascolumnasyelaltolasfilas.
Formatosdeficheros
FormatoBMP
EsteformatofuedesarrolladoporMicrosoftparapermitirunarpidaentrada/salida
pordisco/pantalla.
Entrelascaractersticasdeestetipodealmacenamientodestacalagrancantidadde
nivelesdeprofundidadqueoferta:1bitporpxel(imagende2coloresobinaria),4bits
porpxel(imagende16colores),y24bitsporpxeloloqueeslomismo3bytes
(imagendecolor).
Este formato utiliza compresin sin prdida: RLE o sin comprimir. Adems, el
almacenamientoesbottomleft(seempiezaporlaparteinferiorizquierda),yentrelaza
loscanales.
Lasventajasdeesteformatosonlassiguientes:
Nohayprdidadecalidadenlasimgenes
Lalecturayescriturasonmuyrpidas
-
Elformatoesmuysencillo:cabecera+datos
Encuantoalosinconvenientespodemoscitar:
El tamao de las imgenes es excesivamente grande, sobre todo en
imgenesfotogrficas.
Tamao_imagen=(aprox)ancho*alto*bits_por_pxel
Noesadecuadoparalatransmisinporred.
EspocopopularfueradelosentornosdeMSWindows(aunqueestlibrede
patentes)
Algunasdelasaplicacionesdeesteformatoson:
Aplicacionesquerequieranunarpidasalidaporpantalla.
Aplicaciones donde no deba haber prdida de calidad, aun a costa del
tamao
FormatoTIFF
Fue creado por Aldus (ahora Adobe) pensado en trabajos de impresin de alta
resolucinycalidad.
Esteesunformatomuyflexible,basadoentags(etiquetas)quesonbloquesdedatos
(de formatopredefinido) quecontienencierto tipode informacinsobre la imagen.
Existenmuchostiposdetags(ysepuedencrearnuevos).Unficheropuedecontener
muchostags,unodetrsdeotro.
steesunodelosformatosmsabiertosqueexiste:admitehasta64000canales,un
nmero arbitrario de bits por pxel (hasta enteros o reales de 64 bits), distintos
espacios de color, mltiples imgenes por fichero, cualquier tipo de compresin
existente...
-
Caberesearqueunaimagensepuedealmacenarportiras(cadauna1tag).
Comoventajasdeesteformatotenemos:
Esindependientedelaplataforma,flexibleyampliable.
Puedeadaptarseamuchostiposdenecesidades.
Puedecontener(encapsular)ficherosconotrosformatos.
Losinconvenientesdelformatoson:
Esdemasiadoflexible,porloqueesdifcilcrearunprogramaquesoporte
todaslasopcionesytiposdetags.
Elalmacenamientoentirasesinadecuadoparaciertosusos.
Algunasdelasaplicaciones:
Edicindefotografadealtacalidad,comoimpresindecarteles
Aplicacionesconnecesidadesespeciales,comoimgenesmultiespectrales,
conaltaresolucindecolor...
FormatoJPEG
Esunformatobastantereciente,estmselaboradoyorientadoalalmacenamiento
deimgenesfotogrficas.
Admitetantoimgenesenescaladegrises(1byteporpxel)comoimgenesencolor
RGB(3bytesporpxel).Adems,incluyemecanismosavanzadosdecompresin,que
puedenajustarseadistintosratiosdecompresin.
Unadesusprincipalescaractersticaseslacompresinconprdida,medianteDCT.
Elficheropuedeincluirunaversinreducidaparaprevisualizar la imagenantesde
leerla.
Otroaspectoatenerencuentaesqueseencuentralibredepatentes.
-
Ventajas: Enlamayoradeloscasosconsigueunratiocompresin/calidadmuchomejorque
losotrosformatos.Adems,suniveldecompresinesajustable,tpicamenteentre1:10y1:100
Esunformatomuypopularycasiexclusivoenmuchosmbitos.Inconvenientes: Poseecompresiones/descompresionescomplejasycostosas Noincluyetransparenciasnianimaciones Lainformacinperdidanoserecupera.SitrabajamosconunJPEGguardandoen
discotrascadaoperacin,laimagensevadegradando.Aplicaciones: Seutilizaprcticamenteen todas lasaplicacionesde fotografadigital: captura,
almacenamiento,transmisin,impresin... Noesconvenienteutilizarlosinosepermiteprdidadecalidadosisetrabajacon
dibujos.
Tiposdeimgenes
Las imgenesquevamosa tratar sonbsicamentede tres tipos: imgenesde
intensidad,binariasodecolor.
Imagenbinaria
Laprincipalcaractersticadelasimgenesbinariasesquesoloutilizandosnivelesde
intensidadparasucodificacin:elblancoyelnegro,olosbits1y0.
Enestetipodeimgenes1pxelcorrespondecon1bit,luegoeseltipomssencillo
quenosvamosaencontrar.
Imagendeintensidad
Las imgenesde intensidad tambinsonconocidascomo imgenesenescalade
grises,ysuprincipalcaractersticaesquepermitencodificarunpxelcon255niveles
degrisdistintos:siendoel0=negroyel255=blanco.
Enestetipodeimgenes1pxelsecorrespondecon1byte,deahlos255niveles
permitidos.
-
Imgenesdecolor
Enlaimgenesdecolorcadapxelsecodificacontrescoloresdistintos(rojo,verdey
azul),teniendocadacolorlaprofundidadde1byte.
Por tanto,cadapxel secodificar con3bytes, siendoel nmero total decolores
posiblesdelordende16,7millones.Estoesloquesellamaunaimagenmulticanal,en
estecasode3canales.AunquetambinexistenimgenesRGBAdecuatrocanales
dondeelcuartocanalindicaelniveldetransparenciadeunpxel,conaplicacionesen
visinnocturnaoimgenesporsatlite.Estetipodeimgenesnolasvamosatratar.
Existendosformasbsicasdealmacenamientodeuna imagenRGB,comosonel
entrelazado(dondesealmacenasiguiendoR0 G0 B0 ,R1G1 B1, R2G2 B 2 ...)oelno
entrelazado(dondesealmacenasiguiendoR0R1R2...,G0G1G2...,B0B1B2...).
Perotodoestonoestlimitadoaunosparmetrossinoqueexisteninfinitostipos
posibles,yaqueunniveldegrisouncolorsepuedenrepresentarconmsomenosbits,
loquesellamaprofundidaddecolor(depth).Astambinexistenlasimgenesenpunto
flotantequesontilesparaprocesosintermediosdonde1pxel=1floatodouble.
Tiposdedatosdeunpxel
Unpxelpuedetomarunagrancantidaddetiposdedatosposible,parasaberel
tipodedatodeunpxelbastarconaccederalcampodepthdelaimagen,noobstante
existeunciertonmerodetiposdedatospermitidos,queyaexpusimosenladescripcin
delaestructuraIplImage,peroquevolvemosahaceraquparamayorclaridad:
IPL_DEPTH_8U:Enterossinsignode8bits(unsignedchar)
IPL_DEPTH_8S:Enterosconsignode8bits(signedcharosimplementechar)
IPL_DEPTH_16S:Enterosde16bitsconsigno(shortint)
IPL_DEPTH_32S:Enterosconsignode32bits(int)
-
IPL_DEPTH_32F:Nmerosenpuntoflotanteconprecisinsimplede32bits(float)
Transformacionesafines
Seentiendeportransformacinafncualquiertipoderotacinescaladootraslacin
queseproduzcaen lasdosdireccionesespacialesdelplano.Comotransformaciones
afinesprincipalespodemoscitar:elescalado,larotacinylatraslacin.
Elelementobsicodetodatransformacinafneslamatrizdetransformacin,que
serlaencargadadedefinirlaclaseylosparmetrosdelatransformacinarealizar.As,
tendremossiempreunamatrizasociadatantoparaelescalado,comoparalarotacin,
comoparalatraslacin.
Traslacin
Latraslacintambinesconocidacomodesplazamiento,ysebasaenelcambio
deposicindeunobjetodeacuerdoconunafrmula.
Por lo tanto, la imagen de salida obtenida se relaciona con la entrada de la
siguientemanera:
Img_resultado(x,y)=Img_origen(x+dx,y+dy)
Siendo,dx=desplazamientoenelejehorizontal
dy=desplazamientoenelejevertical
De forma grfica, podemos ejemplificar lo anterior con las siguientes figuras
(suponiendoquecadacuadradoequivaleaunpxel):
Situacin Aplicamostraslacin(1,1) Aplicamostraslacin(1,1)inicialImg_result(x,y)=Img_org(x+1,y+1)Img_rs(x,y)=Img_or(x1,y1)
-
Al trasladar la imagenaparecenpxelesquenoquedandefinidos.Alahorade
programar tomaremosestospxelescomo0, esdecir colornegro.Las funcionesque
utilizaOpencvparalatraslacin,noasignanningnvaloraestosrecuadros,conloque
tenemoslibertadparaasignarleselvalormsconveniente.
El parmetroquenosdefine lascaractersticasde la traslacines lamatrizde
transformacin,queenestecasoesdeltipo:
Matrizdetransformacin=
1 0 dx
0 1 dy
En Opencv toda transformacin afn se puede implementar con la funcin
cvWarpAffine quegeneraunaimagendesalidaalaqueselaaplicalatransformacin
correspondiente.Losparmetrosdeestafuncinsonlossiguientes:
voidcvWarpAffine(constCvArr*src,CvArr*dst,constCvMat*map_matrix,
intflags=CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS,
CvScalarfillval=cvScalarAll(0));
Siendocadaunodeellos:
src:Imagenfuente,alacualseleaplicalatransformacin.
dst:Imagendestino,dondeseobtienelatransformacinrealizada.
map_matrix:Matrizdetransformacin,dedimensiones2x3.
flags:
Lostiposdeinterpolacinpuedenser:
CV_INTER_NN:Interpolacintipovecinomsprximo
CV_INTER_LINEAR:Interpolacinbilineal(eslaqueseutiliza
pordefecto)
CV_INTER_AREA:Seutilizalarelacindepxelyreaparaasignarvalores.Enel
casodeampliarlaimagenactaanlogamenteaelmtodoCV_INTER_NN.
CV_INTER_CUBIC:Interpolacinbicbica.
Loqueacontececonlospxelessobrantes,seconfiguraconlas
siguientesopciones:
CV_WARP_FILL_OUTLIERS:Rellenatodoslospxelesdelaimagen
-
destino.Sialgunosdeelloscorrespondenconpartesquequedan
fueradelaimagenorigen,sonrellenadosaunvalorfijo.
CV_WARP_INVERSE_MAP:Indicaquelamatrizrepresentalarelacin
detransformacininversa,esdecir,delaimagendestinoala
fuente,porloquepuedeserutilizadaparalainterpolacinde
pxeles.
fillval:Eselvalorderellenoqueseusaparadefinirlostrozosque
quedanfueradelaimagen.
Porlotantoesnecesariodefinirpreviamentealaaplicacindeestafuncin,su
matrizdetransformacin.
Ejemplodetraslacin
El siguiente programa implementa una traslacin haciendo uso de los
recursosqueproporcionaOpencv.
#include"cv.h"#include"highgui.h"#include"math.h"#includeintmain(intargc,char**argv){IplImage*src;/*elprimerparmetroquesepaseporconsoladebeserelnombredelfichero*/if(argc==2&&(src=cvLoadImage(argv[1],1))!=0){IplImage*dst=cvCloneImage(src);//clonamoslaimagen//fuente,paraquelaimagendestino//tengalosmismosparmetrosespacialesquelafuenteintdx=40;//desplazamientoenpxelesenelejex;intdy=40;//desplazamientoenpxelesenelejey;CvMat*M=cvCreateMat(2,3,CV_32FC1);//staserlamatrizdetransformacincvmSet(M,0,0,1);//asignamosvalor1alelemento(0,0)cvmSet(M,0,1,0);//asignamosvalor0alelemento(0,1)cvmSet(M,1,0,0);//asignamosvalor0alelemento(1,0)cvmSet(M,1,1,1);//asignamosvalor1alelemento(1,1)cvmSet(M,0,2,dx);//elcuartonmeroindicalospxeles//queserecorrenenelejex
//Paraelloasignamosesenmeroalelemento(0,2)//delamatrizdetransformacincvmSet(M,1,2,dy);//idemejey
-
cvWarpAffine(src,dst,M,CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS,cvScalarAll(0));
//aplicamoslatransformacin,asignandoalospxelesno//definidoselvalor0(colornegro)
cvNamedWindow("origen",1);//dibujamoslaimagendeentradacvNamedWindow("resultado",1);//dibujamoslaimagenresultantecvShowImage("origen",src);cvShowImage("resultado",dst);cvWaitKey(0);//paraterminarelprogramapulsartecla
cvDestroyAllWindows();//destruimostodaslasventanas cvReleaseImage(&src);
cvReleaseImage(&dst);cvReleaseMat(&M);}elseexit(0);cvReleaseImage(&src);return0;}
Comocomentarioadicional,enesteprogramahemoscomprobadoquelaimagen
src ha sido cargada correctamente (src no es un puntero nulo). Esto es bastante
conveniente.
Comosalidadeesteprogramasemuestrandosimgenes,laprimeradeellasesla
imagenorigen, sobre la que vamosa realizar la traslacin. En la segunda figura se
muestralaimagenresultadodeaplicarlatraslacinalaimagenorigen.
Ambasfiguras(6y7),semuestranacontinuacin:
Figura6 Figura7
-
Escalado
Elescaladoesunatransformacinafnquepuedeaumentarodisminuirunobjeto
porundeterminadofactor.
La imagenqueseobtienea lasalidase relacionacon la entradasiguiendo la
siguienteregla:
Imag_destino(x,y)=Imag_origen(ex*x,ey*y)
siendo:
ex:escalaenelejex
ey:escalaenelejey
Dentro del escalado existen dos supuestos bsicos: que la imagen de salida
aumenteconrespectoa la imagendeentrada(aumento), oque la imagendesalida
disminuyaconrespectoalaimagendeentrada(reduccin).Laaplicacindeunauotra
dependerdelfactordeescalaqueintroduzcamos.
Siexoeysonmayoresque1,seproduceunaumentoozoomdelaimagen.
Siexoeysonmenoresque1,seproduceunadisminucindelaimagen.
Siexoeysoniguala1,laimagenquedainvariante.
As,enfuncindelaumentoodeladisminucinquerealicemoslaimagendesalida
quedarcodificadaconundeterminadonmerodepxeles:
Si la imagendeentradaesdetamaopx*py,la imagendesalidaser de
tamaopx/ex*py/ey.
ConlalibreraOpencvexistendosmodosbsicosderealizarestasoperaciones:
podemos utilizar la funcin genrica de transformaciones afines cvWarpAffine, o una
funcinespecficadeescaladocvResizequenosaportaungradomayordeversatilidad.
Tambinresultaimprescindibledefinirlamatrizdetransformacinquenosdictar
-
losparmetrosdelamisma:
Matrizdetransformacin= ex 0 00 ey 0
Ejemplosdeescalado
Enprimer lugar vamosa mostrar un programaqueescala una imagencon la
funcingenricacvWarpAffine.
#include"cv.h"#include"highgui.h"#include"math.h"#includeintmain(intargc,char**argv){IplImage*src;/*elprimerparmetroquesepaseporconsoladebeserelnombredelfichero*/if(argc==2&&(src=cvLoadImage(argv[1],1))!=0){IplImage*dst=cvCloneImage(src);//clonamoslaimagenfuente,paraquelaimagendestino
//tengalosmismosparmetrosespacialesquelafuentefloatex=1;//factordeescalaenelejex;floatey=0.5;//factordeescalaenelejey;CvMat*M=cvCreateMat(2,3,CV_32FC1);//matrizdetransformacin(2x3)cvmSet(M,0,0,ex);//factordeescalaejexcvmSet(M,0,1,0);//asignamosvalor0alelemento(0,1)cvmSet(M,1,0,0);//asignamosvalor0alelemento(1,0)cvmSet(M,1,1,ey);//factordeescalaejeycvmSet(M,0,2,0);//asignamosvalor0alelemento(0,2)cvmSet(M,1,2,0);//asignamosvalor0alelemento(1,2)
cvWarpAffine(src,dst,M,CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS,cvScalarAll(255));//aplicamoslatransformacin,asignandoalospxelesno
//definidoselvalor0(colornegro)
cvNamedWindow("origen",1);//dibujamoslaimagenresultantecvShowImage("origen",src);cvNamedWindow("resultado",1);//dibujamoslaimagenresultantecvShowImage("resultado",dst);cvWaitKey(0);//EsperaapulsarunateclacvDestroyAllWindows();//destruimostodaslasventanas
cvReleaseImage(&src);
-
cvReleaseImage(&dst);cvReleaseMat(&M);}elseexit(0);cvReleaseImage(&src);return0;}
Enlafigura9seapreciaelresultadodeaplicarunescaladoalaimagenoriginal
(figura8).Enestecasonicamentesehaescaladosobreelejevertical(ejey),aplicando
unfactordeescalade0,5,esdecir, reducindolaalamitad.Elejehorizontal(ejex),
permaneceintacto(factordeescala1).
Pasamos a mostrar un segundo programa de escalado utilizando la funcin
cvResize.Enprimerlugaresnecesariocomprenderestafuncinysusparmetros:
voidcvResize(constCvArr*src,CvArr*dst,
intinterpolation=CV_INTER_LINEAR);
Siendo:
src:Imagenfuente.
dst:Imagendestino.
interpolation:Tipodeinterpolacin.Lainterpolacinpuedeserde
lossiguientesmodos:
CV_INTER_NN:Interpolacintipovecinomsprximo
CV_INTER_LINEAR:Interpolacinbilineal(eslaqueseutiliza
pordefecto)
CV_INTER_AREA:Seutilizalarelacindepxelyreapara
asignarvalores.Enelcasodeampliarlaimagenacta
anlogamenteaelmtodoCV_INTER_NN.
Figura8 Figura9
-
CV_INTER_CUBIC:Interpolacinbicbica.
Elusodeestafuncinamplialasposibilidadesdeinterpolacin.Porejemplo,si
ampliamos una imagen la opcin ms adecuada sera la utilizacin de interpolacin
bilinealobicbica.
Tambinesimportanteremarcar,queenestecasoelfactordeescalasedefineen
pxeles, es decir, el propio usuario decide las dimensiones tanto horizontales como
verticalesdelaimagendesalida.
Pasamosamostrarunprograma,queescalaunaimagenconestafuncin:
#include"cv.h"#include"highgui.h"#includecharname0[]="lena.jpg";//enestaocasincargamos//elficheroenelpropioprogramaintmain(){IplImage*imagen=NULL;//inicializoimagenimagen=cvLoadImage(name0,1);//cargamoslaimagenintpx=200;//pxelesenelejexdelaimagenescalada,//esdecir,estamosdefiniendolaescalaXintpy=400;//pxelesenelejexdelaimagenescalada,//esdecir,estamosdefiniendolaescalaY
IplImage*resized=cvCreateImage(cvSize(px,py),IPL_DEPTH_8U,3);//creamoslaestructura//dondeubicaremoslaimagenescalada,//siendopxypylospxelesdelaimagen//destino,esdecir,elpropiofactordeescalacvResize(imagen,resized,CV_INTER_LINEAR);//escaladodelaimagencvNamedWindow("test",1);//representamoslaimagenescalada//(conel1indicamosquela//ventanaseajustealosparmetrosdelaimagen)cvShowImage("test",resized);cvWaitKey(0);//pulsamoscualquierteclaparaterminarelprogramacvDestroyAllWindows();//destruimostodaslasventanascvReleaseImage(&imagen);cvRelase(Image(&resized);return0;}
Enestecasoladefinicindelescaladoesunpocodistinta,yaqueseindicaal
programaelnmerodepxeles,tantoverticalescomohorizontales,queconstituirnla
imagenresultado.
-
Enlafigura10semuestralaimagendeentrada,yenlafigura11obtenemosla
imagenescalada,asignandoalejeverticaldelaimagenescalada400pxelesdelongitud
yasuejehorizontal200pxeles.Elresultadosemuestraacontinuacin:
Rotacin
Larotacinesunatransformacinenlaquelosejesdecoordenadassonrotados
undeterminadongulorespectoalorigen.
Lasoperacionesenlascoordenadasquesellevanacaboenlarotacinsepueden
sintetizarenlasiguienterelacin:
Imagen_resultado(x,y)=Imagen_inicial(xcos +ysen , xsen +ycos )
siendo =nguloderotacin
Esdecir,siReslamatrizderotacin:
cos() sen()
sen() cos()
yresunvectorcolumna:
x
y
EntoncesImagen_destino(x,y)=Imagen_origen(Rr)
Figura10Figura11
-
Conlamatrizdefinidaanteriormentelarotacinserealizarespectoalpunto(0,0)
pero si queremos definir un centro de rotacin en el punto (cx, cy), la matriz de
transformacincambia,siendodelsiguientemodo:
cos() sen() cxcxcos()cysen()
sen() cos() cy+cxsen()cycos()
Puesahorasolorestaaplicarestosconceptosparaimplementarlaoperacinde
rotacin.Opencvofrecedosposibilidadesdistintaspararealizarestaoperacin.Porun
lado est el uso de la funcin genrica para transformaciones afines cvWarpAffine
acompaada de la funcin cv2DRotationMatrix que calcula la matriz de rotacin
necesaria.PorotroladodisponemosdelafuncincvGetQuadrangleSubPixquerealizala
mismafuncinquelaanteriorconalgunamatizacin:
Lafuncin cvWarpAffine exigequetanto imagendeentradacomodesalida
tengan el mismo tipo de datos, mientras que cvGetQuadrangleSubPix permite
compaginartiposdedatosdistintos.
LafuncincvWarpAffinepuededejarpartedelaimagendesalidasinrellenaro
sin modificar suvalor anterior, mientrasqueen cvGerQuadrangleSubPix todos los
puntos de la imagen de salida toman un valor, incluso aquellos que no estn
directamentedefinidossonasignadosalvalordelpxelmsprximo.
-
Ejemplosderotacin
Comenzamosestudiandoelcasoderotarunaimagenutilizandolafuncingenrica
cvWarpAffine, ya estudiada. Sin embargo, debemos introducir la funcin
cv2DRotationMatrixparaelclculodelamatrizdetransformacin:
CvMat*cv2DRotationMatrix(CvPoint2D32fcenter,doubleangle,double
scale,CvMat*map_matrix);
Siendo:
center:Centroderotacindelaimagen(unacoordenadaen2D)
angle:Elnguloderotacinengrados.Valorespositivosdeeste
ngulorotanlaimagenenelsentidocontrarioalasagujasdelreloj.
Elorigendecoordenadassesuponequeseencuentraenlaesquina
superiorizquierdadelaimagen.ElngulosedaenGRADOS.
map_matrix:Punteroalaubicacindelamatrizdedimensiones2x3.
Eslasalidadelafuncin,esdecir,lamatrizderotacindeseada.
Pasamos a mostrar un programa que utiliza estas estructuras para rotar una
imagen:
#include"cv.h"#include"highgui.h"#includecharname0[]="pasillo1.jpg";intmain(){IplImage*imagen=NULL;//inicializoimagenimagen=cvLoadImage(name0,1);//cargamoslaimagenarotar
//definimoslaimagendesalidadonde//serepresentaraalaimagenrotadaIplImage *rotated=cvCreateImage(cvGetSize(imagen),IPL_DEPTH_8U, imagen>nChannels);
CvPoint2D32fcenter;//definimoselelcentrodelarotacinintangle=30;//definimoselnguloderotacinengradosCvMat*mapMatrix=cvCreateMat(2,3,CV_32FC1);//definimoslasdimensionesdelamatrizdetransformacincenter.x=160;//asignamoslacoordenadaxdelarotacinquedeseemoscenter.y=120;//asignamoslacoordenadaydelarotacinquedeseemoscv2DRotationMatrix(center,angle,1.0,mapMatrix);//calculalosvaloresdemapMatrixcvWarpAffine(imagen,rotated,mapMatrix,CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS, cvScalarAll(0));//realizalatransformacinderotacin
-
cvNamedWindow("origen",1);//representalaimagenrotadacvShowImage("origen",imagen);cvNamedWindow("resultado",1);//representalaimagenrotadacvShowImage("resultado",rotated);cvWaitKey(0);//esperaapulsarteclaparafinalizarcvDestroyAllWindows();//destruimostodaslasventanascvReleaseImage(&imagen);cvReleaseImage(&rotated);cvReleaseMat(&mapMatrix);return0;}
Alaplicarunarotacinsobreunaimagencualquiera(figura12),conuntamaode
320x240pxeles.Obtenemoslaimagenrotadaqueseobservaenlafigura13.Elcentro
de la rotacincoincideeneste casoconel centro de la imagen (160x120). Seha
definidounnguloarbitrarioderotacinde30grados.Lapartedelaimagenrotadaque
quedasindefinir,sehafijadoacolorblanco.
El segundo caso de rotacin bajo anlisis utiliza la funcin
cvGetQuadrangleSubPix, enestecasodefinimoslamatrizdetransformacindeforma
artesanal.Vamosaestudiarlosparmetrosdelafuncin:
voidcvGetQuadrangleSubPix(constCvArr*src,CvArr*dst,constCvMat*
map_matrix);
Siendo:
src:Imagenquequeremosrotar.
dst:Trozodelaimagensrcquetomamos.Ennuestrocasotomaremosla
imagenentera(dimensionesdesrcigualesalasdedst).
map_matrix:Lamatrizdetransformacin(3x2).
Figura12 Figura13
-
Loqueenrealidadhaceestafuncinestomarpxelesdelaimagenoriginalcon
unaprecisinmayor, y losrepresentaen la imagendestinoconesamayorprecisin,
aplicandolarelacindetransformacindefinidaporlamatriz.
Elsiguienteprogramamuestracomorotarunaimagenconesafuncin:
#include"cv.h"#include"highgui.h"#include"math.h"intmain(intargc,char**argv){IplImage*src;if(argc==2&&(src=cvLoadImage(argv[1],1))!=0)//cargamoslaimagenensrc{IplImage*dst=cvCloneImage(src);//hacemosunacopiadelaimagenendst,paraque//laimagendestinoposealosmismosparmetrosquelaorigenintangle=25;//definimoselnguloderotacinfloatm[6];//componentesdelamatrizMCvMatM=cvMat(2,3,CV_32F,m);//matrizdetransformacinintw=src>width;//anchuraenpxelesdelaimageninth=src>height;//alturaenpxelesdelaimagen
m[0]=(float)(cos(angle*2*CV_PI/180.));//elementosdelamatrizm[1]=(float)(sin(angle*2*CV_PI/180.));m[2]=w*0.5f;m[3]=m[1];m[4]=m[0];m[5]=h*0.5f;
cvGetQuadrangleSubPix(src,dst,&M);//aplicamoslarotacincvNamedWindow("origen",1);//representamoslarotacincvShowImage("origen",src);cvNamedWindow("resultado",1);//representamoslarotacincvShowImage("resultado",dst);cvWaitKey(0);//pulsarteclaparaterminarcvDestroyAllWindows();cvReleaseImage(&dst);}elseexit(0);cvReleaseImage(&src);return0;}
Alaplicarlarotacinsobrelafigura14obtenemoslaimagenrepresentadaenla
figura15.Elcentrodelarotacineselcentrodelaimagenyesngulodegiroseha
fijadoa25grados.Comonovedaddestacaelrellenodelapartedelaimagenrotadaque
quedasindefinir,conlosvaloresquestaposeeenelcontornodelamisma.
-
Binarizacindeimgenes
Enestaseccinsepretendedaraentender lasarmasconlasquenosprovee
Opencv para el cambio de codificacin entre imgenes. As, el principal objetivo es
encontrarunafuncinoconjuntodefuncionesquerealicenlamismaoperacinquelas
estructurasgraythreshyim2bwrealizanenMatlab.
Portanto,debemossercapacesdetomarunaimagenenescaladegrises(imagen
deintensidad)yconvertirlaenimagenbinaria,mediantelaaplicacindeunumbral.Todos
losvaloressuperioresalvalorumbralsernbinarizadosa1ylosquenosuperenese
valorloserna0.
OpencvproporcionalafuncincvThresholdparaelprocesodebinarizacin.Vamos
aanalizarlamsenprofundidad:
voidcvThreshold(constCvArr*src,CvArr*dst,doublethreshold,double
max_value,
intthreshold_type);
Siendo:
src:Imagenorigen.Podrtenercodificacinde8bitsode32bits
enpuntoflotante.
dst:Imagendesalida.Deberserde8bitsodeigualtipoquela
sealdeentrada.
threshold:Elvalorumbraldelabinarizacin.
max_value:Valormximoautilizarparalosdostiposdebinarizacinmsfrecuentes
Figura14 Figura15
-
(CV_THRESH_BINARYyCV_THRESH_BINARY_INV). threshold_type:Eltipodebinarizacinarealizar.Exponemoslos
tiposexistentes:
threshold_type=CV_THRESH_BINARY:dst(x,y)=max_value,si
src(x,y)>threshold
0encasocontrario.
threshold_type=CV_THRESH_BINARY_INV:dst(x,y)=0,si
src(x,y)>thresholdmax_valueencasocontrario.
threshold_type=CV_THRESH_TRUNC:dst(x,y)=threshold,si
src(x,y)>threshold
src(x,y)encasocontrario.
threshold_type=CV_THRESH_TOZERO:dst(x,y)=src(x,y),si
(x,y)>threshold
0encasocontrario.
threshold_type=CV_THRESH_TOZERO_INV:dst(x,y)=0,si
src(x,y)>threshold
src(x,y)encasocontrario.
ApartedeestatransformacinOpencvtambinnosdalaposibilidaddetransformar
unaimagenRGBenotraenescaladegrises,utilizandolafuncincvCvtColor:
voidcvCvtColor(constCvArr*src,CvArr*dst,intcode);
Siendo:
src:Laimagenorigencodificadaen8bitsoenpuntoflotante
dst:Laimagendestinocodificadaen8bitsoenpuntoflotante
code:Definelaoperacindeconversinallevaracabo.Esta
operacinsedefineutilizandolasconstantes
CV_2.
Caberemarcarqueexistengrancantidaddecombinacionesquesepueden
llevaracabo.Nosotrosestamosinteresadosenlatransformacin
BGR2GRAY.Todaslascombinacionesposiblessepuedenconsultarenel
manualdelafuncin.
-
Ejemplodebinarizacin
Pasamosaenunciarunejemplodeestafuncin:
#include"cv.h"#include"highgui.h"#include"math.h"intmain(){IplImage*src;//imagendecolorbaseIplImage*colorThresh;//contendrlaimagendecolorbinarizadaIplImage*gray;//contendrlaimagenconvertidaenescaladegrisesIplImage*grayThresh;//imagenbinariaconseguida//apartirdelaimagenenescaladegrisesintthreshold=120;//definimoselvalorumbralintmaxValue=255;//definimoselvalormximointthresholdType=CV_THRESH_BINARY;//definimosel//tipodebinarizacin
src=cvLoadImage("out4553.pgm",1);//cargamosimagendecolorcolorThresh=cvCloneImage(src);//copiamosesaimagendecolorgray=cvCreateImage(cvSize(src>width,src>height),IPL_DEPTH_8U,1);//laimagendeintensidadtendrlamismaconfiguracin//quelafuenteperoconunsolocanal
cvCvtColor(src,gray,CV_BGR2GRAY);//pasamoslaimagendecolor//aescaladegrisesgrayThresh=cvCloneImage(gray);//copiamoslaimagenenescala//degrises(trucoanterior)
cvNamedWindow("src",1);//representamoslaimagendecolorcvShowImage("src",src);
cvNamedWindow("gray",1);//representamoslaimagendeintensidadcvShowImage("gray",gray);
cvThreshold(src,colorThresh,threshold,maxValue,thresholdType);//binarizamoslaimagendecolor
cvThreshold(gray,grayThresh,threshold,maxValue,thresholdType);//binarizamoslaimagendeintensidad
cvNamedWindow("colorThresh",1);//representamoslaimagen//decolorbinarizadacvShowImage("colorThresh",colorThresh);
cvNamedWindow("grayThresh",1);//representamoslaimagen//deintensidadbinarizadacvShowImage("grayThresh",grayThresh);
cvWaitKey(0);//pulsamosteclaparaterminar
cvDestroyWindow("src");//destruimostodaslasventanas
-
cvDestroyWindow("colorThresh");cvDestroyWindow("gray");cvDestroyWindow("grayThresh");
cvReleaseImage(&src);//eliminamostodaslasimgenescvReleaseImage(&colorThresh);cvReleaseImage(&gray);cvReleaseImage(&grayThresh);return0;}
Lafigura16representaunaimagendecolor.Enlafigura17seharepresentadola
imagenanteriorperoconvertidaaescaladegrises.Sobreesaimagenenescaladegrises
seharealizado la binarizacin, conumbral ennivel de intensidad120, obteniendo la
instantneadelafigura18.
Figura16 Figura17 Figura18
-
Operacionesconmatrices
Opencvofertavariasfuncionesdetratamientodematrices,lamayoradeellasse
basanen la realizacindeoperacioneselementoporelemento.Sinembargo,nuestro
estudiosebasaenclculomatricialenconjuntoynoelementoporelemento,conloque
noscentraremosenlamultiplicacindematricestradicionalyenelclculodelainversa.
Inversindematrices
Alahoradeinvertirmatricesdeformamanualsebarajandosotresmtodosms
populares.Opencvtambinpermitedefinirelmtodoqueseconsideremsconveniente,
oferta tres caminosdistintos por los que invertir unamatriz, todosellos dentro de la
funcincvInvert.Lafuncineslasiguiente:
doublecvInvert(constCvArr*src,CvArr*dst,intmethod=CV_LU);
Ladescripcindelosparmetroseslasiguiente:
src:Lamatrizquesedeseainvertir
dst:Matrizdesalida,contienelainversadelamatrizdeentrada
method:Mtododeinversin.Exponemoslosmtodosadjuntandosu
descripcineningls,paranodistorsionarsusignificado:
CV_LUGaussianeliminationwithoptimalpivotelementchose
CV_SVDSingularvaluedecomposition(SVD)method
CV_SVD_SYMSVDmethodforasymmetricpositivelydefinedmatrix
Ejemplodeinvertirmatrices
Exponemosunejemplo sencillo para concretar el funcionamiento de la funcin
anterior:
#include"cv.h"#include"highgui.h"#include"math.h"#include
-
intmain(){CvMat*M=cvCreateMat(2,2,CV_64FC1);//matrizainvertirCvMat*P=cvCreateMat(2,2,CV_64FC1);//contendrlamatrizinversa
cvmSet(M,0,0,1.0);//definimoslamatrizainvertircvmSet(M,0,1,2.0);cvmSet(M,1,0,3.0);cvmSet(M,1,1,7.0);
cvInvert(M,P,CV_LU);//invertimoslamatrizcvReleaseMat(&M);cvReleaseMat(&P);return0;}
Sisedesearavisualizarelresultadodeestainversindematricesporpantalla,la
expresinqueseobtendraseralasiguiente:
1 23 71
= 7 23 1
Multiplicacindematrices
La funcin de multiplicar dos matrices no est directamente implementada en
Opencv,perosexistenfuncionesquerealizanlamultiplicacinconalgnmatizaadido.
Estamoshablandode la funcin cvMulMatAdd queaparte demultiplicar dosmatrices
tambin suma una tercera al producto, para utilizar esta funcin debemos definir
convenientementelasmatricesutilizandocvInitHeader.Pasamosadarunadescripcinde
estasdosestructuras:
CvMat*cvInitMatHeader(CvMat*mat,introws,intcols,inttype,void*
data=NULL, intstep=CV_AUTOSTEP
);
Siendo:
mat:Punteroalacabeceradelamatrizquesevaainicializar
rows:Nmerodefilasenlamatriz
cols:Nmerodecolumnasenlamatriz
type:Tipodeloselementosdelamatriz
-
data:Punteroalacabeceradelamatrizparalaasignacindedatos
step:tamaocompletoenbytesdeunafiladedatos,pordefectose
tomaelmnimopasoposible(CV_AUTOSTEP),esdecir,sesuponequeno
quedanhuecosentredosfilasconsecutivasdelamatriz
LafuncincvMatMulAddevalaelproductodedosmatricesyaadelaterceraal
mismo:
cvMatMulAdd(srcasrcbsrccdst)
siendo:
srca:Primeramatrizamultiplicar
srcb:Segundamatrizamultiplicar
src:Matrizasumaralproductoanterior
dst:Matrizqueguardaelresultadofinaldelasoperaciones
Ejemplodemultiplicacin
ElsiguienteprogramarealizaelproductoMc=Ma*Mb,delsiguientemodo:
#include"cv.h"#include"highgui.h"#include"math.h"#include
intmain(){//Elindicedecolumnaeselquecorreprimerodoublea[]={1,2,3,4,5,6,7,8,9,10,11,12};//definimosloselementosdelamatriza
doubleb[]={1,5,9,2,6,10,3,7,11,4,8,12};//definimosloselementosdelamatrizb
doublec[9];//declaramosloselementosdelamatrizc
CvMatMa,Mb,Mc;//declaramoslasmatrices
cvInitMatHeader(&Ma,3,4,CV_64FC1,a,CV_AUTOSTEP);//RellenamoslasmatricescvInitMatHeader(&Mb,4,3,CV_64FC1,b,CV_AUTOSTEP);cvInitMatHeader(&Mc,3,3,CV_64FC1,c,CV_AUTOSTEP);
cvMatMulAdd(&Ma,&Mb,0,&Mc);//realizamoselproductodelasmatrices(3x4)y(4x3)
-
printf("multiplicacion%f%f%f%f%f%f",c[0],c[1],c[2],c[3],c[4],c[5]);return0;}
Portantoesteprogramaejecutalaoperacinsiguiente,conelresultadoquese
muestraenlaecuacinsiguiente.
1 2 3 45 6 7 89 10 11 121 5 92 6 103 7 114 8 12= 30 70 11070 174 278110 278 446
-
BIBLIOGRAFA
Pasamosacitar, lamayorpartedelabibliografautilizadaenlaconfeccindel
manual:
LeedsGuidetoOpencv.CxCoreReferenceManual
Autor:DrewMorgan
ltimaactualizacin:3Noviembrede2006
http://www.comp.leeds.ac.uk/vision/opencv/opencvref_cxcore.htm
CvReferenceManual
Autor:DrewMorgan
ltimaactualizacin:3deNoviembrede2006
http://www.comp.leeds.ac.uk/vision/opencv/opencvref_cv.html
HighGUIReferenceManual
Autor:EdLawson
http://cs.gmu.edu/~vislab/opencvdocs/ref/opencvref_highgui.htm
OpenSourceComputingVisionLibrary.ReferenceManual.Intel
http://www.intel.com/technology/computing/opencv/
ImageProcessingandAnalysisReference
Autor:FranciscoBlanesGmez/LuisM.Jimnez
ltimaactualizacin:17deMayode2006
http://isa.umh.es/pfc/rmvision/opencvdocs/ref/OpenCVRef_ImageProcessing.htm
BasicStructuresandOperationsReference
Autor:FranciscoBlanesGmez/LuisM.Jimnez
-
ltimaactualizacin:17deMayode2006
http://isa.umh.es/pfc/rmvision/opencvdocs/ref/OpenCVRef_BasicFuncs.htm
ProcesamientoAudiovisual.
Autor:GinsGarcaMateos
IntroductiontoprogrammingwithOpenCV
Autor:GadyAgam
ltimaactualizacin:27deEnerode2006
http://www.cs.iit.edu/~agam/cs512/lectnotes/opencvintro/opencvintro.html
ExperimentalandObsoleteFunctionalityReference
Autor:MauricioFerreira/AurelioMoraes
ltimaactualizacin:8deagostode2007
http://www.tecgraf.pucrio.br/~malf/opencv/ref/opencvref_cvaux.htm
ObjectRecognitionReference
http://isa.umh.es/pfc/rmvision/opencvdocs/ref/OpenCVRef_ObjectRecognition.htm
OpenCvIHighGui
Autor:DavidMilln
ltimaactualizacin:20deMarzode2005
http://www.artresnet.com/david/tutorial.jsp?id=4
Pxelprocessing
Autor:BerndJhne/SpringerVerlag
http://mmc36.informatik.uniaugsburg.de/mediawiki/data/3/37/VSP0607
Lecture2new.pdf
IntroductiontoOpencv
-
Autor:VadimPisarevsky
ltimaactualizacin:9deJuniode2007
http://fsa.ia.ac.cn/files/OpenCV_China_2007June9.pdf
OpenSourceComputerVisionLibrary
ltimaactualizacin:14deSeptiembrede2006
http://wwwrobotics.cs.umass.edu/Documentation/OpenCV
LushManual
Autor:YannLeCun/LeonBottou
ltimaactualizacin:24deNoviembrede2002
http://lush.sourceforge.net/lushmanual/8193ae9d.html
ForodeOpencvenYahooGroups:ForooficialdelosusuariosdeOpencv
http://tech.dir.groups.yahoo.com/dir/Computers___Internet/Software/Open_Source
-
GNUFreeDocumentationLicenseGNUFreeDocumentationLicense
Version1.2,November2002
Copyright(C)2000,2001,2002FreeSoftwareFoundation,Inc.
51FranklinSt,FifthFloor,Boston,MA021101301USA
Everyoneispermittedtocopyanddistributeverbatimcopies
ofthislicensedocument,butchangingitisnotallowed.
0.PREAMBLE
ThepurposeofthisLicenseistomakeamanual,textbook,orotherfunctionalandusefuldocument"free"inthesenseoffreedom:toassureeveryonetheeffectivefreedomtocopyandredistributeit,withorwithoutmodifyingit,eithercommerciallyornoncommercially.
Secondarily,thisLicensepreservesfortheauthorandpublisherawaytogetcreditfortheirwork,whilenotbeingconsideredresponsibleformodificationsmadebyothers.
ThisLicenseisakindof"copyleft", whichmeansthatderivativeworksof thedocumentmustthemselvesbefreeinthesamesense.ItcomplementstheGNUGeneralPublicLicense,whichisacopyleftlicensedesignedforfreesoftware.
Wehave designed this License in order to use it for manuals for free software, because freesoftwareneedsfreedocumentation:afreeprogramshouldcomewithmanualsprovidingthesamefreedomsthatthesoftwaredoes.ButthisLicenseisnotlimitedtosoftwaremanuals;itcanbeusedforanytextualwork,regardlessofsubjectmatterorwhetheritispublishedasaprintedbook.WerecommendthisLicenseprincipallyforworkswhosepurposeisinstructionorreference.
1.APPLICABILITYANDDEFINITIONS
ThisLicenseappliestoanymanualorotherwork,inanymedium,thatcontainsanoticeplacedbythecopyrightholdersayingitcanbedistributedunderthetermsofthisLicense. Suchanoticegrants a worldwide, royaltyfree license, unlimited in duration, to use that work under theconditionsstatedherein.The"Document",below,referstoanysuchmanualorwork.Anymemberofthepublicisalicensee,andisaddressedas"you".Youacceptthelicenseifyoucopy,modifyordistributetheworkinawayrequiringpermissionundercopyrightlaw.
-
A"ModifiedVersion"oftheDocumentmeansanyworkcontainingtheDocumentoraportionofit,eithercopiedverbatim,orwithmodificationsand/ortranslatedintoanotherlanguage.
A"SecondarySection"isanamedappendixorafrontmattersectionoftheDocumentthatdealsexclusivelywiththerelationshipofthepublishersorauthorsoftheDocumenttotheDocument'soverallsubject(ortorelatedmatters)andcontainsnothingthatcouldfalldirectlywithinthatoverallsubject.(Thus,iftheDocumentisinpartatextbookofmathematics,aSecondarySectionmaynotexplainanymathematics.) Therelationshipcouldbeamatter ofhistoricalconnectionwiththesubjectorwithrelatedmatters,oroflegal,commercial,philosophical,ethicalorpoliticalpositionregardingthem.
The"InvariantSections"arecertainSecondarySectionswhosetitlesaredesignated,asbeingthoseofInvariantSections,inthenoticethatsaysthattheDocumentisreleasedunderthisLicense.IfasectiondoesnotfittheabovedefinitionofSecondarythenitisnotallowedtobedesignatedasInvariant.TheDocumentmaycontainzeroInvariantSections.IftheDocumentdoesnotidentifyanyInvariantSectionsthentherearenone.
The"CoverTexts"arecertainshortpassagesoftextthatarelisted,asFrontCoverTextsorBackCoverTexts,inthenoticethatsaysthattheDocumentisreleasedunderthisLicense. AFrontCoverTextmaybeatmost5words,andaBackCoverTextmaybeatmost25words.
A"Transparent"copyoftheDocumentmeansamachinereadablecopy,representedinaformatwhosespecificationisavailabletothegeneralpublic,thatissuitableforrevisingthedocumentstraightforwardly with generic text editors or (for images composed of pixels) generic paintprogramsor(fordrawings)somewidelyavailabledrawingeditor,andthatissuitableforinputtotext formatters or for automatic translation to a variety of formats suitable for input to textformatters. AcopymadeinanotherwiseTransparentfileformatwhosemarkup,orabsenceofmarkup, has been arranged to thwart or discourage subsequent modification by readers is notTransparent.AnimageformatisnotTransparentifusedforanysubstantialamountoftext.Acopythatisnot"Transparent"iscalled"Opaque".
ExamplesofsuitableformatsforTransparentcopiesincludeplainASCIIwithoutmarkup,Texinfoinputformat,LaTeXinputformat,SGMLorXMLusingapubliclyavailableDTD,andstandardconformingsimpleHTML,PostScript orPDFdesignedforhumanmodification. Examples oftransparent image formats include PNG, XCF and JPG. Opaque formats include proprietaryformatsthatcanbereadandeditedonlybyproprietarywordprocessors,SGMLorXMLforwhichtheDTDand/orprocessingtoolsarenotgenerallyavailable,andthemachinegeneratedHTML,PostScriptorPDFproducedbysomewordprocessorsforoutputpurposesonly.
-
The"TitlePage"means,foraprintedbook,thetitlepageitself,plussuchfollowingpagesasareneededtohold,legibly,thematerialthisLicenserequirestoappearinthetitlepage.Forworksinformats which do not have any title page as such, "Title Page" means the text near the mostprominentappearanceofthework'stitle,precedingthebeginningofthebodyofthetext.
Asection"EntitledXYZ"meansanamedsubunitoftheDocumentwhosetitleeitherispreciselyXYZorcontainsXYZinparenthesesfollowingtextthattranslatesXYZinanotherlanguage.(HereXYZ stands for a specific section name mentioned below, such as "Acknowledgements","Dedications","Endorsements",or"History".)To"PreservetheTitle"ofsuchasectionwhenyoumodifytheDocumentmeansthatitremainsasection"EntitledXYZ"accordingtothisdefinition.
TheDocumentmayincludeWarrantyDisclaimersnexttothenoticewhichstatesthatthisLicenseappliestotheDocument.TheseWarrantyDisclaimersareconsideredtobeincludedbyreferenceinthisLicense,butonlyasregardsdisclaimingwarranties:anyotherimplicationthattheseWarrantyDisclaimersmayhaveisvoidandhasnoeffectonthemeaningofthisLicense.
2.VERBATIMCOPYING
You may copy and distribute the Document in any medium, either commercially ornoncommercially,providedthatthisLicense,thecopyrightnotices,andthelicensenoticesayingthis License applies to the Document are reproduced in all copies, and that youaddnootherconditionswhatsoevertothoseofthisLicense.Youmaynotusetechnicalmeasurestoobstructorcontrolthereadingorfurthercopyingofthecopiesyoumakeordistribute. However,youmayacceptcompensationinexchangeforcopies.Ifyoudistributealargeenoughnumberofcopiesyoumustalsofollowtheconditionsinsection3.
Youmayalsolendcopies,underthesameconditionsstatedabove,andyoumaypubliclydisplaycopies.
3.COPYINGINQUANTITY
If youpublish printed copies (or copies in media that commonly have printed covers) of theDocument,numberingmorethan100,andtheDocument'slicensenoticerequiresCoverTexts,youmustenclosethecopiesincoversthatcarry,clearlyandlegibly,alltheseCoverTexts:FrontCoverTextsonthefrontcover,andBackCoverTextsonthebackcover.Bothcoversmustalsoclearlyandlegiblyidentifyyouasthepublisherofthesecopies.Thefrontcovermustpresentthefulltitlewithallwordsofthetitleequallyprominentandvisible.Youmayaddothermaterialonthecoversinaddition.Copyingwithchangeslimitedtothecovers,aslongastheypreservethetitleoftheDocumentandsatisfytheseconditions,canbetreatedasverbatimcopyinginotherrespects.
-
Iftherequiredtextsforeithercoveraretoovoluminoustofitlegibly,youshouldputthefirstoneslisted(asmanyasfitreasonably)ontheactualcover,andcontinuetherestontoadjacentpages.
IfyoupublishordistributeOpaquecopiesoftheDocumentnumberingmorethan100,youmusteitherincludeamachinereadableTransparentcopyalongwitheachOpaquecopy,orstateinorwitheachOpaquecopyacomputernetworklocationfromwhichthegeneralnetworkusingpublichasaccesstodownloadusingpublicstandardnetworkprotocolsacompleteTransparentcopyoftheDocument,freeofaddedmaterial.Ifyouusethelatteroption,youmusttakereasonablyprudentsteps,whenyoubegindistributionofOpaquecopiesinquantity,toensurethatthisTransparentcopywillremainthusaccessibleatthestatedlocationuntilatleastoneyearafterthelasttimeyoudistributeanOpaquecopy(directlyorthroughyouragentsorretailers)ofthateditiontothepublic.
It is requested, but not required, that you contact the authors of the Document well beforeredistributinganylargenumberofcopies,togivethemachancetoprovideyouwithanupdatedversionoftheDocument.
4.MODIFICATIONS
YoumaycopyanddistributeaModifiedVersionoftheDocumentundertheconditionsofsections2and3above,providedthatyoureleasetheModifiedVersionunderpreciselythisLicense,withtheModifiedVersionfillingtheroleoftheDocument,thuslicensingdistributionandmodificationoftheModifiedVersiontowhoeverpossessesacopyofit.Inaddition,youmustdothesethingsintheModifiedVersion:
A.UseintheTitlePage(andonthecovers,ifany)atitledistinctfromthatoftheDocument,andfromthoseofpreviousversions(whichshould,iftherewereany,belistedintheHistorysectionoftheDocument).Youmayusethesametitleasapreviousversioniftheoriginalpublisherofthatversiongivespermission.
B.ListontheTitlePage,asauthors,oneormorepersonsorentitiesresponsibleforauthorshipofthemodificationsintheModifiedVersion,togetherwithatleastfiveoftheprincipalauthorsoftheDocument(allofitsprincipalauthors,ifithasfewerthanfive),unlesstheyreleaseyoufromthisrequirement.
C.StateontheTitlepagethenameofthepublisheroftheModifiedVersion,asthepublisher.
D.PreserveallthecopyrightnoticesoftheDocument.
E. Addan appropriate copyright notice for your modifications adjacent to the other copyrightnotices.
F.Include,immediatelyafterthecopyrightnotices,alicensenoticegivingthepublicpermissiontousetheModifiedVersionunderthetermsofthisLicense,intheformshownintheAddendum
-
below.
G.PreserveinthatlicensenoticethefulllistsofInvariantSectionsandrequiredCoverTextsgivenintheDocument'slicensenotice.
H.IncludeanunalteredcopyofthisLicense.
I.PreservethesectionEntitled"History",PreserveitsTitle,andaddtoitanitemstatingatleastthetitle,year,newauthors,andpublisheroftheModifiedVersionasgivenontheTitlePage.IfthereisnosectionEntitled"History"intheDocument,createonestatingthetitle, year,authors,andpublisheroftheDocumentasgivenonitsTitlePage,thenaddanitemdescribingtheModifiedVersionasstatedintheprevioussentence.
J.Preservethenetworklocation,ifany,givenintheDocumentforpublicaccesstoaTransparentcopyoftheDocument, andlikewisethenetworklocationsgivenintheDocumentforpreviousversionsitwasbasedon.Thesemaybeplacedinthe"History"section.Youmayomitanetworklocationforaworkthatwaspublishedatleast fouryearsbeforetheDocumentitself, orif theoriginalpublisheroftheversionitreferstogivespermission.
K. For any section Entitled "Acknowledgements" or "Dedications", Preserve the Title of thesection, and preserve in the section all the substance and tone of each of the contributoracknowledgementsand/ordedicationsgiventherein.
L.PreservealltheInvariantSectionsoftheDocument,unalteredintheirtextandintheirtitles.Sectionnumbersortheequivalentarenotconsideredpartofthesectiontitles.
M. Delete any section Entitled "Endorsements". Such a section may not be included in theModifiedVersion.
N.DonotretitleanyexistingsectiontobeEntitled"Endorsements"ortoconflictintitlewithanyInvariantSection.
O.PreserveanyWarrantyDisclaimers.
IftheModifiedVersionincludesnewfrontmattersectionsorappendicesthatqualifyasSecondarySectionsandcontainnomaterial copiedfromtheDocument,youmayatyouroptiondesignatesomeorallofthesesectionsasinvariant.Todothis,addtheirtitlestothelistofInvariantSectionsintheModifiedVersion'slicensenotice.Thesetitlesmustbedistinctfromanyothersectiontitles.
YoumayaddasectionEntitled"Endorsements",provideditcontainsnothingbutendorsementsofyourModifiedVersionbyvariouspartiesforexample,statementsofpeerrevieworthatthetexthas
beenapprovedbyanorganizationastheauthoritativedefinitionofastandard.
YoumayaddapassageofuptofivewordsasaFrontCoverText,andapassageofupto25wordsasaBackCoverText,totheendofthelistofCoverTextsintheModifiedVersion. Onlyonepassage of FrontCover Text and one of BackCover Text may be added by (or through
-
arrangementsmadeby)anyoneentity.IftheDocumentalreadyincludesacovertextforthesamecover,previouslyaddedbyyouorbyarrangementmadebythesameentityyouareactingonbehalfof,youmaynotaddanother;butyoumayreplacetheoldone,onexplicitpermissionfromthepreviouspublisherthataddedtheoldone.
Theauthor(s)andpublisher(s)oftheDocumentdonotbythisLicensegivepermissiontousetheirnamesforpublicityforortoassertorimplyendorsementofanyModifiedVersion.
5.COMBININGDOCUMENTS
YoumaycombinetheDocumentwithotherdocumentsreleasedunderthisLicense,underthetermsdefinedinsection4aboveformodifiedversions,providedthatyouincludeinthecombinationalloftheInvariantSectionsofalloftheoriginaldocuments,unmodified,andlistthemallasInvariantSectionsofyourcombinedworkin its licensenotice, andthatyoupreserveall their WarrantyDisclaimers.
ThecombinedworkneedonlycontainonecopyofthisLicense,andmultipleidenticalInvariantSectionsmaybereplacedwithasinglecopy.IftherearemultipleInvariantSectionswiththesamenamebutdifferentcontents,makethetitleofeachsuchsectionuniquebyaddingattheendofit,inparentheses,thenameoftheoriginalauthororpublisherofthatsectionifknown,orelseauniquenumber.MakethesameadjustmenttothesectiontitlesinthelistofInvariantSectionsinthelicensenoticeofthecombinedwork.
In the combination, you must combine any sections Entitled "History" in the various originaldocuments, forming one section Entitled "History"; likewise combine any sections Entitled"Acknowledgements", and any sections Entitled "Dedications". You must delete all sectionsEntitled"Endorsements".
6.COLLECTIONSOFDOCUMENTS
YoumaymakeacollectionconsistingoftheDocumentandotherdocumentsreleasedunderthisLicense,andreplacetheindividualcopiesofthisLicenseinthevariousdocumentswithasinglecopy that is included in the collection, provided that you follow the rules of this License forverbatimcopyingofeachofthedocumentsinallotherrespects.
Youmayextractasingledocumentfromsuchacollection,anddistributeitindividuallyunderthisLicense,providedyouinsertacopyofthisLicenseintotheextracteddocument,andfollowthisLicenseinallotherrespectsregardingverbatimcopyingofthatdocument.
-
7.AGGREGATIONWITHINDEPENDENTWORKS
AcompilationoftheDocumentoritsderivativeswithotherseparateandindependentdocumentsorworks, in or ona volumeof a storage or distribution medium, is called an"aggregate" if thecopyrightresultingfromthecompilationisnotusedtolimitthelegalrightsofthecompilation'susersbeyondwhattheindividualworkspermit.WhentheDocumentisincludedinanaggregate,thisLicensedoesnotapplytotheotherworksintheaggregatewhicharenotthemselvesderivativeworksoftheDocument.
IftheCoverTextrequirementofsection3isapplicabletothesecopiesoftheDocument,theniftheDocumentislessthanonehalfoftheentireaggregate,theDocument'sCoverTextsmaybeplacedoncoversthatbrackettheDocumentwithintheaggregate,ortheelectronicequivalentofcoversiftheDocumentisinelectronicform.Otherwisetheymustappearonprintedcoversthatbracketthewholeaggregate.
8.TRANSLATION
Translation is considered a kind of modification, so you may distribute translations of theDocumentunder thetermsofsection4. ReplacingInvariantSections with translations requiresspecialpermissionfromtheircopyrightholders,butyoumayincludetranslationsofsomeorallInvariantSectionsinadditiontotheoriginalversionsoftheseInvariantSections.Youmayincludea translation of this License, and all the license notices in the Document, and any WarrantyDisclaimers,providedthatyoualsoincludetheoriginalEnglishversionofthisLicenseandtheoriginalversionsofthosenoticesanddisclaimers.IncaseofadisagreementbetweenthetranslationandtheoriginalversionofthisLicenseoranoticeordisclaimer,theoriginalversionwillprevail.
If a sectionin theDocument is Entitled"Acknowledgements", "Dedications", or"History", therequirement(section4)toPreserveitsTitle(section1)willtypicallyrequirechangingtheactualtitle.
9.TERMINATION
Youmaynotcopy,modify,sublicense,ordistributetheDocumentexceptasexpresslyprovidedforunderthisLicense. Anyotherattempttocopy,modify,sublicenseordistributetheDocumentisvoid,andwillautomaticallyterminateyourrightsunderthisLicense.However,partieswhohavereceivedcopies,orrights,fromyouunderthisLicensewillnothavetheirlicensesterminatedsolongassuchpartiesremaininfullcompliance.
10.FUTUREREVISIONSOFTHISLICENSE
TheFreeSoftwareFoundationmaypublishnew,revisedversionsoftheGNUFreeDocumentationLicensefromtimetotime.Suchnewversionswillbesimilarinspirittothepresentversion,but
-
maydifferindetailtoaddressnewproblemsorconcerns.Seehttp://www.gnu.org/copyleft/.
EachversionoftheLicenseisgivenadistinguishingversionnumber.IftheDocumentspecifiesthataparticularnumberedversionofthisLicense"oranylaterversion"appliestoit,youhavetheoptionoffollowingthetermsandconditionseitherofthatspecifiedversionorofanylaterversionthathasbeenpublished(notasadraft)bytheFreeSoftwareFoundation.IftheDocumentdoesnotspecifyaversionnumberofthisLicense,youmaychooseanyversioneverpublished(notasadraft)bytheFreeSoftwareFoundation.
LicenciaHistoria del documentoInstalacin y compilacinGNU Free Documentation License