You are on page 1of 42

CHAPTER 3

Getting to know OpenCV


OpenCV Primitive Data Types
OpenCV c vi data type c s. Nhng data type ny khng c s t gc nhn ca C, nhng chng tt c l cc structure n gin, v ta s xem chng nh nguyn t. Bn c th xem xt chi tit cc structure m t nh sau (cng nh cc structure khc) trong cxtypes.h header file, m .../OpenCV/cxcore/include directory ca ci ct OpenCV. n gin nht ca nhng types ny l CvPoint. CvPoint l structure n gin vi hai integer members, x v y. CvPoint c hai anh em: CvPoint v CvPoint3D32f. Ci u c cng hai members x v y, m c hai l cc s floating-point. Ci sau cng cha phn t th ba, z.
CvSize ging anh h ca CvPoint. Cc phn t ca n l width v height, m c hai l integer. Nu bn mun cc s floating-point, dng anh hc CvSize2D32f cousin ca CvSize. CvRect mt con khc ca CvPoint v CvSize; n cha bn member: x, y, width, v height. (Trong trng hp bn lo lng, con chu ny c chp nhn.)

Cui cng nhng khng km l CvScalar, m l mt tp bn s double-precision. Khi memory khng l vn , CvScalar thng c dng biu din mt, hai, hay ba s thc (trong nhng trng hp ny, cc thnh phn khng cn n gin c b qua). CvScalar c mt member val, m l mt pointer n mt array cha bn s doubleprecision floating-point. Tt c nhng data type ny c cc constructor method c nn nh cvSize() (nhn chung* constructor c cng tn nh structure type nhng vi character u tin khng hoa). Nh rng y l C v khng phi C++, do nhng constructors ny ch l cc inline function m nhn mt list cc argument v return structure mong mun vi cc value c t thch hp. Cc inline constructor cho cc data type k trong Table 3-1cvPointXXX(), cvSize(), cvRect(), v cvScalar()l cc k hu ch v chng lm code khng ch d hn vit m cn d c hn. Gi s bn mun v mt rectangle trng gia (5, 10) v (20, 30); bn c th n gin gi:
cvRectangle( myImg, cvPoint(5,10), cvPoint(20,30), cvScalar(255,255,255) );

Table 3-1. Structures for points, size, rectangles, v scalar tuples Structure cha Represents CvPoint int x, y Point in image CvPoint2D32f float x, y Points in 2 CvPoint3D32f float x, y, z Points in 3 CvSize int width, height Size of image CvRect int x, y, width, Portion of height image CvScalar double val[4] RGBA value cvScalar() l trng hp c bit: n c ba constructor. u tin, gi l cvScalar(), ly

mt, hai, ba, hay bn argument v gn nhng argument ny cho cc phn t tng

ng ca val[]. Constructor th hai l cvRealScalar(); n ly mt argument, m n gn vo val[0] trong khi setting cc entry khc thnh 0. Variant cui cng l cvScalarAll(), m ly mt argument n nhng t tt c bn phn t ca val[] thnh cng argument .

Matrix v Image Types

Hnh 3-1 cho thy th bc class hay structure ca ba image types. Khi dng OpenCV, bn s chm trn lp li IplImage data type. Bn hin thy n nhiu ln trong chng trc. IplImage l structure c s c dng encode ci ta nhn chung gi l cc image. Nhng image ny c th l grayscale, color, four-channel (RGB+alpha), v mi channel c th cha bt k trong vi type ca cc s integer hay floatingpoint. Do , kiu ny l chung hn image three-channel 8-bit RGB c khp ni m tc thi n trong u.* OpenCV cung cp lng ln cc operator hu ch m hot ng trn nhng images ny, gm cc tool resize images, trch cc channel ring, tm thy cc value ln nht hay nh nht ca mt channel c th, cng hai images, threshold mt image, v hn na. In chng ny ta s xem xt nhng kiu ny ca cc operator cn thn.

Hnh 3-1. Ngay c qua OpenCV c thc hin trong C, cc structure c dng trong OpenCV c mt thit k hng i tng; v hiu qu, IplImage c dn t CvMat, m c dn t CvArr

Trc khi ta c th tho lun cc image chi tit, ta cn quan st mt data type khc: CvMat, OpenCV matrix structure. D OpenCV c thc hin ton b trong C, quan h gia CvMat v IplImage l hi ging vi th bc trong C++. Cho tt c cc ngha v cc mc ch, IplImage c th c ngh nh c dn t CvMat. Do , iu tt nht hiu l lp c s (nn l) trc khi c hiu cc phc tp thm ca lp dn xut. Lp th ba, gi l CvArr, c th c ngh nh mt abstract base class m t CvMat t n c dn. Bn s thng thy CvArr (hay, chnh xc hn, CvArr*) trong cc function prototypes. Khi n xut hin, n chp nhn chuyn CvMat* hay IplImage* cho routine.

CvMat Matrix Structure

C hai iu bn cn bit trc khi ta chm vo matrix business. u tin, khng c vector construct trong OpenCV. Bt c khi no ta mun mt vector, ta ch dng mt matrix vi mt ct (hay mt hng, nu ta muoons mt hon v hay kt hp vector). Th hai, khi nim ca mt matrix trong OpenCV l c phn tru tng hn khi nim bn hc trong lp i s tuyn tnh. V c th, cc phn t ca mt matrix t chng khng l cc s n gin. V d, routine m m to mt two-dimensional matrix mi c prototype sau:

cvMat* cvCreateMat ( int rows, int cols, int type );

y type c th l bt k ca mt list di cc predefined type theo dng: CV_<bit_depth>(S|U|F) C<number_of_channels>. Do , matrix c th gm cc 32-bit floats (CV_32FC1), ca cc unsigned integer 8-bit triplets (CV_8UC3), hay v s cc element khc. Mt element ca CvMat khng cn thit l mt s n. C th biu din nhiu gi tr cho mt entry n trong matrix cho php ta lm nhiu th nh biu din

nhiu channel mu trong mt RGB image. Cho mt image n gin cha cc knh red, green v blue, hu ht cc image operator s c p dng cho mi channel ring (tr phi ngc li c lu ). V bn trong, structure ca CvMat tng i n gin, nh c thy trong Example 3-1 (bn c th thy iu ny bi m /opencv/cxcore/include/cxtypes.h). Cc matrix c mt width, height, type, step (chiu di ca mt row theo cc byte, khng ints hay floats), v mt pointer n mt data array (v mt vi th m ta cha th ni). Bn c th truy cp nhng members ny trc tip bi referencing li mt pointer n CvMat hay, cho mt vi element ph bin hn, bi dng cc accessor function c cung cp. V d, ly size ca mt matrix, bn c th ly thng tin bn mun mt trong bi gi cvGetSize(CvMat*), m tr v mt CvSize structure, hay bi truy cp height v width c lp vi cc constructs nh matrix->height v matrix->width.
Example 3-1. CvMat structure: the matrix header
typedef struct CvMat { int type; int step; int* refcount; // cho dng ch bn trong union { uchar* ptr; short* s; int* i; float* fl; double* db; } data; union { int rows; int height; }; union { int cols; int width; }; } CvMat;

Thng tin ny nhn chung c refer n nh matrix header. Nhiu routines phn bit gia header v data, ci sau l memory m data element tr n. Cc matrix c th c to theo mt trong vi cch. Cc hu ht ph bin l dng cvCreateMat(), m is thc s thun tin s kt hp ca nhiu atomic function cvCreateMatHeader() v cvCreateData(). cvCreateMatHeader() to CvMat structure khng cp memory cho data, trong khi cvCreateData() handles cp pht data. i khi ch cvCreateMatHeader() c i hi, mt trong v bn cp data cho vi nguyn nhn khc hay v bn cha thc s cn cp n. Method th ba dng cvCloneMat(CvMat*), m to matrix mi t mt ci hin c.* Khi matrix khng cn cn na, n c th c gii phng bi gi cvReleaseMat(CvMat**). List trong Example 3-2 tm tt cc function ta va m t cng nhng ci khc m lin quan mt thit.
Example 3-2. Matrix creation v release
// to mt matrix rows by cols ca kiu type. // CvMat* cvCreateMat( int rows, int cols, int type ); // to only matrix header without allocating data // CvMat* cvCreateMatHeader( int rows, int cols, int type ); // Khi to header on existing CvMat structure // CvMat* cvInitMatHeader( CvMat* mat, int rows, int cols, int type, void* data = NULL, int step = CV_AUTOSTEP ); // Like cvInitMatHeader() but allocates CvMat as well.

Tng t vi nhiu OpenCV structures, c mt constructor gi l cvMat() m to mt CvMat structure. Routine ny khng thc s cp pht memory; n ch to header (iu ny tng t vi cvInitMatHeader()). Nhng method ny l cch tt ly vi data bn c nm di, ng gi n bi tr matrix header n n nh trong Example 3-3, v chy n qua cc routine m x l cc OpenCV matrice.
Example 3-3. To mt OpenCV matrix vi data c nh
// to an OpenCV Matrix containing some fixed data. // float vals[] = { 0.866025, -0.500000, 0.500000, 0.866025 }; CvMat rotmat; cvInitMatHeader( &rotmat, 2, 2, CV_32FC1, vals );

// CvMat cvMat( int rows, int cols, int type, void* data = NULL ); // Allocate a new matrix just like the matrix mat. // CvMat* cvCloneMat( const cvMat* mat ); // Free the matrix mat, both header v data. // void cvReleaseMat( CvMat** mat );

Mt khi ta c mt matrix, c nhiu th ta c th lm vi n. Cc tc v n gin nht l query cc kha cnh ca nh ngha array v truy cp data. query matrix, ta c cvGetElemType( const CvArr* arr ), cvGetDims( const CvArr* arr, int* sizes=NULL ), v cvGetDimSize( const CvArr* arr, int index ). Ci u tin tr v mt integer constant biu din kiu cc phn t c lu trong array (iu ny s bng vi ci ging CV_8UC1, CV_64FC4, ). Ci th hai ly array v mt pointer ty chn n mt integer; n tr v s cc chiu (hai cho trng hps ta ang quan tm, nhng v sau ta s trm chn cc N-dimensional matrix nh cc object). Nu integer pointer l khc null th n s lu height v width(hay N dimensions) ca array c cung cp. Function cui ly mt integer nhn bit chiu ca ci quan tm v n gin tr v extent ca matrix trong chiu .*

Accessing Data in Your Matrix


The easy way

C ba cch truy cp data trong matrix: cch d, cch kh, v cch ng. Cch d nht ly mt phn t thnh phn ca mt array l bng CV_MAT_ELEM() macro. Macro ny (xem Example 3-4) ly matrix, type ca phn t c nhn, v s row v column v sau tr v phn t.
Example 3-4. Trruy cp mt matrix bng CV_MAT_ELEM() macro
CvMat* mat = cvCreateMat( 5, 5, CV_32FC1 ); float element_3_2 = CV_MAT_ELEM( *mat, float, 3, 2 );

Under the hood macro ny ch gi macro CV_MAT_ELEM_PTR(). CV_MAT_ELEM_PTR() (xem Example 3-5) ly cc argument matrix v row v column ca element c quan tm v tr v (khng ngc nhin) mt pointer n phn t c ch nh. Mt khc bit quan trng gia CV_MAT_ELEM() v CV_MAT_ELEM_PTR() l CV_MAT_ELEM() thc s p pointer thnh kiu ch nh trc khi de-referencing n. Nu bn thch t gi tr hn ch c n, bn c th gi CV_MAT_ELEM_PTR() trc tip; trong trng hp ny, tuy nhin, bn phi cast pointer tr v thnh kiu thch hp.
Example 3-5. t mt gi tr n trong matrix dng CV_MAT_ELEM_PTR() macro
CvMat* mat = cvCreateMat( 5, 5, CV_32FC1 ); float element_3_2 = 7.7; *( (float*)CV_MAT_ELEM_PTR( *mat, 3, 2 ) ) = element_3_2;

Khng may, nhng ci ny macros tnh li pointer cn trong mi li gi. iu ny c ngha gim st pointer thnh phn t c s ca vng data ca matrix, tnh mt offset ly address ca thng tin bn quan tm, v sau thm offset vo c s c tnh. Do , mc d nhng macro ny l d dng, chng c th khng l cch tt nht truy cp mt matrix. iu ny l c bit ng khi bn c k hoch truy cp tt c cc element trong mt matrix tun t. Ta s n ngay vi cch tt nht hon thnh nhim v quan trng ny.

The hard way


Hai macros c tho lun trong The easy way ch ph hp truy cp cc mng mt hay hai chiu (nh li cc mng mt chiu, hay cc vector, thc s ch l n-by1 cc matrix). OpenCV cung cp cc c ch lm vic vi cc mng a chiu. Tht ra OpenCV cho php cho mt N-dimensional matrix ni chung m c th c nhiu chiu nh bn thch. truy cp data mt matrix tng qut, ta dng h cc function cvPtr*D v cvGet*D k trong Examples 3-6 v 3-7. cvPtr*D family cha cvPtr1D(), cvPtr2D(), cvPtr3D(), v cvPtrND() . . . . Mi ci trong ba ci u tin ly mt tham s pointer matrix CvArr* theo sau bi s thch hp ca cc integer cho cc index, v mt argument ty chn nhn din kiu ca tham s output. Cc routine return mt pointer n element quan tm. Bng cvPtrND(), argument th hai l mt pointer n mt array cc integer cha s thch hp ca cc index. Ta s return function ny sau. (Trong cc prototype m theo sau, bn s cng llwu cc argument ty chn thch hp; ta s address nhng ci ny khi ta cn chng.)
Example 3-6. Pointer truy cp vo cc matrix structures
uchar* cvPtr1D( const CvArr* arr, int idx0, int* type = NULL ); uchar* cvPtr2D( const CvArr* arr, int idx0, int idx1, int* type = NULL ); uchar* cvPtr3D( const CvArr* arr, int idx0, int idx1, int idx2, int* type = NULL ); uchar* cvPtrND( const CvArr* arr, int* idx, int* type = NULL, int create_node = 1, unsigned* precalc_hashval = NULL );

c hon ton data, c mt dng khc ca cc function cvGet*D, k trong Example 3-7, m tng t vi nhng cais trong Example 3-6 nhng return gi tr thc ca matrix element.
Example 3-7. CvMat v IplImage element functions
double cvGetReal1D( const CvArr* arr, int idx0 ); double cvGetReal2D( const CvArr* arr, int idx0, int idx1 ); double cvGetReal3D( const CvArr* arr, int idx0, int idx1, int idx2 ); double cvGetRealND( const CvArr* arr, int* idx ); CvScalar cvGet1D( const CvArr* arr, int idx0 ); CvScalar cvGet2D( const CvArr* arr, int idx0, int idx1 ); CvScalar cvGet3D( const CvArr* arr, int idx0, int idx1, int idx2 ); CvScalar cvGetND( const CvArr* arr, int* idx );

Return type ca cvGet*D l double cho bn ca cc routine v CvScalar cho bn ci khc. iu ny c ngha rng c th c vi lng ph c ngha khi dng nhng

function ny. Chng nn c dng ch ni thun li v hiu qu; ngc li, tt hn l dng cvPtr*D. Mt nguyn nhn tt hn dng cvPtr*D() l bn c th dng nhng pointer functions ny c li truy cp n mt im c th trong matrix v sau dng i s pointer di chuyn quanh matrix t . iu quan trng phi nh rng cc channel l lin tip trong multichannel matrix. V d, trong matrix hai chiu ba channel biu din cc byte red, green, blue (RGB), matrix data c lu: rgbrgbrgb . . . . Do , di chuyn mt pointer ca kiu thch hp n channel tip theo, ta cng 1. Nu ta mun i n pixel tip theo hay tp cc element, ta cng v offset bng vi s cc channel (trong trng hp ny l 3). Mo khc bit phn t bc trong matrix array (xem Examples 3-1 v 3-3) l chiu di theo bytes ca mt row trong matrix. Trong structure , cc ct hay mt mnh rng khng di chuyn gia cc hng matrix v, hin qu my, matrix hay image allocation c lm thnh bin bn byte gn nht. Do mt matrix ca ba byte rng s c cp thnh bn byte vi ci cui c b qua. Cho nguyn nhn ny, nu ta ly mt byte pointer n data element th ta thm bc vo pointer chuyn n n row tip theo trc tip bn di im ca tapoint. Nu ta c mt matrix cc s nguyn hay floating-point v tng ng int hay float pointers cho mt data element, ta s bc n hng tip theo bi thm step/4; cho cc double, ta cng step/8 (iu ny ch ly mt lng m C s t ng nhn cc offset ta cng bi byte size ca data type). Mt t tng t vi cvGet*D l cvSet*D trong Example 3-8, m t mt matrix hay image element bng mt li gi, v cc functions cvSetReal*D() v cvSet*D(), m c th c dng set cc value ca cc elements ca mt matrix hay image.
Example 3-8. Set element functions for CvMat hay IplImage.
void cvSetReal1D( CvArr* arr, int idx0, double value ); void cvSetReal2D( CvArr* arr, int idx0, int idx1, double value ); void cvSetReal3D( CvArr* arr, int idx0, int idx1, int idx2, double value ); void cvSetRealND( CvArr* arr, int* idx, double value ); void cvSet1D( CvArr* arr, int idx0, CvScalar value ); void cvSet2D( CvArr* arr, int idx0, int idx1, CvScalar value ); void cvSet3D( CvArr* arr, int idx0, int idx1, int idx2, CvScalar value ); void cvSetND( CvArr* arr, int* idx, CvScalar value );

Nh mt thun li i km, ta cng c cvmSet() v cvmGet(), m c dng khi lm vic vi cc matrix mt channel floating-point. Chng l rt n gin: Do li gi n function tin li cvmSet(),
cvmSet( mat, 2, 2, 0.5000 ); cvSetReal2D( mat, 2, 2, 0.5000 ); double cvmGet( const CvMat* mat, int row, int col ) void cvmSet( CvMat* mat, int row, int col, double value )

l ging vi li gi n cvSetReal2D function tng ng,

The right way

Vi tt c cc accessor function ny, bn c th ngh rng khng g thm ni. Tht ra, bn s him khi dng bt k trong cc hm set v get. Hu ht thi gian, vision l hot ng i hi processor, v bn s mun lm cc th trong hu ht cch hiu qu c th. Khng cn thit ni, i qua nhng interface functions ny l khng hiu qu. Thay vo , bn nn lm i s pointer ring v n gin de-reference cch ca bn vo matrix. Qun l cc pointers t bn l c bit quan trng khi bn

mun lm g vi mi element trong mt array (gi thit khng c OpenCV routine m c th thc hin nhim v ny cho bn). truy cp trc tip vo phn bn trong ca mt matrix, tt c bn thc s cn bit l data c lu tun t theo th t qut th, trong cc ct (x) l bin chy nhanh nht. Cc channel c chen vo, m c ngha rng, trong trng hp ca mt multichannel matrix, chng l th t chy nhanh nht. Example 3-9 cho thy mt v d cch iu ny c th c lm.
Example 3-9. Cng tt c cc elements trong mt three-channel matrix
float sum( const CvMat* mat ) { float s = 0.0f; for(int row=0; row<mat->rows; row++ ) { const float* ptr = (const float*)(mat->data.ptr + row * mat->step); for( col=0; col<mat->cols; col++ ) { s += *ptr++; } } return( s ); }

Khi tnh pointer trong matrix, nh rng matrix element data l hp nht. Do , khi de-referencing pointer ny, bn phi nhn din ng element ca hp nht ny ly pointer type ng. Sau , offset pointer , bn phi dng step element ca matrix. Nh lu trc y, step element l theo byte. an ton, tt nht lm i s pointer theo byte v sau cast type thch hp, trong trng hp ny l float. Mc d CVMat structure c khi nim height v width tng thch vi IplImage structure c, ta dng the cc hng v ct cp nht hn thay vo. Cui cng, lu rng ta tnh li ptr cho mi hng hn l n gin bt u lc bt u v sau tng pointer mi ln c. iu ny c th dng nh d, nhng v CvMat data pointer c th ch tr n mt ROI vi trong mt array ln hn, khng c m bo data s lin tip vi cc hng.

Arrays of Points

Mt vn m s n thng xuynv l quan trng hiul khc nhau gia mt multidimensional array (hay matrix) of multidimensional objects v mt array ca mt chiu cao hn m cha ch cc one-dimensional object. Gi thit, v d, bn c n points theo ba chiu m bn mun chuyn qua OpenCV function m nhn mt argument kiu CvMat* (hay, ng hn, cvArr*). C bn cch hin nhin bn c th lm iu ny, v n tuyt i nghim tc nh rng chng khng cn thit tng ng. Mt method s l dng mt two-dimensional array ca type CV32FC1 vi n rows v ba columns (n-by-3). Tng t, bn c th dng mt two-dimensional array ca ba row v n columns (3-by-n). Bn c th cng dng mt array vi n rows v mt column (n-by-1) ca type CV32FC3 hay mt array vi mt row v n columns (3-by-1). Mt vi trong nhng trng hp ny c th c chuyn t do t ci sang ci khc (c ngha bn c th ch chuyn mt ni ci khc c mong) nhng nhng ci khc khng th. hiu l do, quan st memory layout c thy trong Hnh 3-2. Nh bn c th thy trong hnh, cc point c nh x trong memory theo cng cch cho ba trong bn trng hp va c m t trn nhng khc cho ci cui.

Hnh 3-2. Mt tp mi point, mi ci c biu din bi ba s floating-point, t trong bn array m mi ci dng mt structure hi khc; trong ba trng hp memory layout kt qu l ng nht, nhng trng hp mt l khc

Trng hp ngay c phc tp hn cho trng hp ca mt N-dimensional array ca cc c-dimensional point. iu ct yu l v tr ca bt k point cho trc c cho bi bi cng thc:

= (row) N cols N channels + (col ) N channels + (channel )

trong Ncols v Nchannels l s columns v channels, tng ng.* T cng thc ny ci c th thy rng, nhn chung, mt N-dimensional array ca cc c-dimensional object l khng ging nh mt (N + c)-dimensional array ca cc one-dimensional object. Trong trng hp c bit N = 1 (chng hn cc vectors biu din mt trong nh nby-1 hay 1-by-n arrays), c mt suy bin c bit (c bit, cc tng ng c thy trong Hnh 3-2) m c th i khi c c thun li v hiu sut. Chi tit cui lin qua cc OpenCV data type chng hn CvPoint2D v CvPoint2D32f. Nhng data type ny c nh ngha nh cc C structure v do c memory layout c nh ngha nghim chnh. V c th, cc s integer hay floating-point m nhng structures ny hp thnh l th t channel. Nh mt kt qu, mt one-dimensional C-style array ca cc object ny c cng memory layout nh mt n-by-1 hay mt 1by-n array ca type CV32FC2. L do tng t p dng cho cc array ca cc structure ca type CvPoint3D32f.

IplImage Data Structure/*/

Vi tt c iu trong tay, by gi d dng tho lun IplImage data structure. Trong object thc cht ny l mt CvMat nhng vi vi goodies thm c t trong n lm matrix thch hp cho mt image. Structure ny ban u c nh ngha nh mt phn ca Image Processing Library (IPL) ca Intel.* nh ngha chnh xc ca IplImage structure c thy trong Example 3-10.
Example 3-10. IplImage header structure
typedef struct _IplImage { int nSize; int ID; int nChannels; int alphaChannel; int depth; char colorModel[4]; char channelSeq[4]; int dataOrder; int origin; int align; int width; int height;

Nghe tht hay, ta mun tho lun chc nng ca vi trong nhng variable ny. Vi l bnh thng, nhng nhiu l rt quan trng hiu cch OpenCV thng dch v lm vic vi cc image. Sau width v height, depth v nChannels ph bin l hu ht ch yu tip theo. Bin depth ly mt trong mt tp cc value nh ngha trong ipl.h, m (khng may) khng chnh xc cc value ta trm chn khi quan st cc matrix. iu ny v cho cc image ta hng n lm vic vi depth v s cc channel ring r (bt c matrix routines ta hng n refer chng ng thi). Cc depth cth c k trong Table 3-2.
Table 3-2. OpenCV image types Macro
IPL_DEPTH_8U IPL_DEPTH_8S IPL_DEPTH_16S IPL_DEPTH_32S IPL_DEPTH_32F IPL_DEPTH_64F

struct _IplROI* roi; struct _IplImage* maskROI; void* imageId; struct _IplTileInfo* tileInfo; int imageSize; char* imageData; int widthStep; int BorderMode[4]; int BorderConst[4]; char* imageDataOrigin; } IplImage;

Image pixel type Unsigned 8-bit integer (8u) Signed 8-bit integer (8s) Signed 16-bit integer (16s) Signed 32-bit integer (32s) 32-bit fl oating-point single-precision (32f) 64-bit fl oating-point doubleprecision (64f)

Cc value c th cho nChannels l 1, 2, 3, hay 4. Hai members quan trng tip theo l origin v dataOrder. Origin variable c th ly mt trong hai value: IPL_ORIGIN_TL hay IPL_ORIGIN_BL, tng ng bi gc ta c t mt trong upper-left hay lower-left corners ca image, tng ng. Vic thiu origin chun (upper vi lower) l ngun quan trng ca error trong cc computer vision routines. V c th, ph thuc vo ni image n, operating system, codec, storage format, v hn na c th tt c nh hng v tr ca ta ca image c th. V d, bn c th ngh bn ly mu cc pixel t mt khun mt trong phn t nh ca mt image trong khi bn thc s ly mu mt ci o trong phn t y. Tt nht l kim tra system ln u tin bi v ni bn ngh bn ang vn hnh trn mt image patch. dataOrder c th l mt trong IPL_DATA_ORDER_PIXEL hay IPL_DATA_ORDER_PLANE.* Gi tr ny nhn bit c hay khng data nn c gi bng ci multiple channels sau khi ci khc cho mi pixel (interleaved, trng hp bnh thng), hay hn l tt c channel c b thnh cc image plane vi cc plane t mt ci sau khi ci khc. Parameter widthStep cha s cc byte gia cc im trong cng ct v cc hng lin tip (tng t vi step parameter ca CvMat c tho lun trc). Variable width khng tnh khong cch v mi hng c th c ging vi mt s no cc byte c c x l nhanh hn ca image; do c th c vi k h gia kt thc ca hng i v bt u hng (i + 1). Parameter imageData cha mt pointer n hng u tin ca image data. Nu c vi plane ring trong image (nh khi dataOrder = IPL_DATA_ORDER_PLANE) th chng c t lin tip nh cc image ring vi cc hng height*nChannels theo tng, nhng thng thng chng c interleaved sao cho s hng bng vi height v vi mi hng cha cc interleaved channel theo th t. Cui cng c region of interest (ROI) thc t v quan trng, m thc s l mt instance ca mt IPL/IPP structure khc, IplROI. Mt IplROI cha mt xOffset, a yOffset, height, width, v coi, ni COI vit tt cho channel of interest.* tng pha sau ROI l, mt khi n c t, cc function m thng thng lm vic trn ton b image s

thay vo hot ng ch trn tp con ca image nhn din bi ROI. Tt c OpenCV functions s dng ROI nu c t. Nu COI c t thnh mt value khc khng th vi operator s lm vic ch trn channel c ch nh. Khng may, nhiu OpenCV functions b qua parameter ny.

Accessing Image Data

Khi lm vic vi image data ta thng cn lm sao cho nhanh chng v hiu qu. iu ny gi rng ta khng nn t kht ph vic trn ca gi cc accessor function nh cvSet*D hay tng ng ca chng. Tht ta, ta thch truy cp data bn trong ca image theo hu ht cch trc tip nh c th. Bng kin thc v bn trong IplImage structure, ta by gi c th hiu cch tt nht lm iu ny. Ngay c qua cc well-optimized routines trong OpenCV m hon thnh nhiu trong cc nhim v ta cn thc hin trn image, s lun lun c cc nhim v m khng c routine ng gi sn trong library. Xem xt trng hp ca mt three-channel HSV [Smith78] image m trong ta mun set saturation v value thnh 255 (cc value cc i cho mt 8-bit image) while hue khng bin i. Ta c th l tt nht iu ny bi t handling cc pointers vo image, nh ta lm vi cc matrix trong Example 3-9. Tuy nhin, c vi khc bit ph m ny sinh t khc bit gia IplImage v CvMat structures. Example 3-11 cho thy cch nhanh nht.
Example 3-11. Maxing out (saturating) only the S v V parts of an HSV image
void saturate_sv( IplImage* img ) { for( int y=0; y<img->height; y++ ) { uchar* ptr = (uchar*) ( img->imageData + y * img->widthStep ); for( int x=0; x<img->width; x++ ) { ptr[3*x+1] = 255; ptr[3*x+2] = 255; } } }

Ta n gin tnh pointer ptr trc tip nh u ca hng y lin qua. T , ta dereference saturation v value ca ct x. V y l threechannel image, v tr channel c trong column x l 3*x+c. Mt khc bit quan trng gia trng hp IplImage v the trng hp CvMat l hnh x ca imageData, so vi element data ca CvMat. Data element ca CvMat l hp nht, do bn phi nhn bit pointer type m bn mun dng. imageData pointer l byte pointer (uchar*). Ta hin bit rng data c tr n khng nht thit type uchar, m c ngha rngkhi lm i s pointer trn imagesbn c th n gin thm widthStep (cng c o theo byte) khng lo v data type thc n sau khi php cng, khi bn cast pointer kt qu thnh data type bn cn. recap: khi lm vic vi cc matrix, bn phi scale down offset v the data pointer c th l nonbyte type; khi lm vic vi images, bn c th dng offset as is v data pointer lun lun l byte type, do bn c th ch cast ton b th khi bn sn sng dng n.

More on ROI v widthStep

ROI v widthStep c quan trng thc hnh ln, v trong nhiu trng hp chng tng tc cc tc v computer vision bi cho php code x l ch vng nh ca image. H tr cho ROI v widthStep l ph bin trong OpenCV:* Mi function cho php hot ng c gii hn trn mt vng ph. bt ROI bt hay tt, dng cvSetImageROI() v cvResetImageROI() functions. Cho trc mt vng ph ch nht mong mun theo dng ca CvRect, bn c th chuyn image pointer v ch nht n cvSetImageROI() bt ROI; tt ROI bi chuyn image pointer n cvResetImageROI().
void cvSetImageROI( IplImage* image, CvRect rect ); void cvResetImageROI( IplImage* image );

thy cch ROI c dng, hy gi s ta mun load mt image v modify vi region ca image . Code trong Example 3-12 c mt image v sau sets x, y, width, v height ca ROI mong mun v cui cng mt integer value thm vo tng ROI region. Program sau t ROI dng thun li ca inline cvRect() constructor.

iu quan trng l release ROI bng cvResetImageROI(), ngc li display s quan st ROI v display nghim tc ch ROI region.
Example 3-12. dng ImageROI to increment tt c of the pixels in a region
// roi_add <image> <x> <y> <width> <height> <add> #include <cv.h> #include <highgui.h> int main(int argc, char** argv) { IplImage* src; if( argc == 7 && ((src=cvLoadImage(argv[1],1)) != 0 )) { int x = atoi(argv[2]); int y = atoi(argv[3]); int width= atoi(argv[4]); int height = atoi(argv[5]); int add = atoi(argv[6]); cvSetImageROI(src, cvRect(x,y,width,height)); cvAddS(src, cvScalar(add),src); cvResetImageROI(src); cvNamedWindow( Roi_Add, 1 ); cvShowImage( Roi_Add, src ); cvWaitKey(); } return 0; }

Hnh 3-3 cho thy kt qu ca thm 150 vo blue channel ca image ca con mo vi mt ROI c tm trn mt n, dng code t Example 3-12.

Hnh 3-3. Kt qu cng 150 v mt ROI ca mt con mo

Ta c th c c cng hiu ng bi dng thng minh widthStep. lm iu ny, ta to mt image header khc v t width v height bng interest_rect width v height. Ta cng cn set image origin (upper left hay lower left) cng vi interest_img. Tip theo ta set widthStep ca subimage thnh widthStep ca interest_img ln hn; cch ny, bc bi cc hng theo cc bc subimage bn t thch hp bt u ca dng tip theo ca subregion bng vi image ln hn. Ta cui cng set subimage imageData pointer thnh bt u ca subregion mong mun, nh c thy trong Example 3-13.

Example 3-13. dng alternate widthStep method to increment tt c of the pixels of interest_img by 1
// Assuming IplImage *interest_img; and // CvRect interest_rect; // dng widthStep to get a region of interest // // (Alternate method) // IplImage *sub_img = cvCreateImageHeader( cvSize( interest_rect.width, interest_rect.height ), interest_img->depth, interest_img->nChannels ); sub_img->origin = interest_img->origin; sub_img->widthStep = interest_img->widthStep; sub_img->imageData = interest_img->imageData + interest_rect.y * interest_img->widthStep + interest_rect.x * interest_img->nChannels; cvAddS( sub_img, cvScalar(1), sub_img ); cvReleaseImageHeader(&sub_img);

Do , v sao bn nn mun dng mo widthStep khi setting v resetting ROI dng nh l qua thun li? Nguyn nhn l c nhng ln khi bn mun set v chng hn gi nhiu subregions ca mt image tch cc trong khi x l, but ROI c th ch c lm ni tip v phi c t v reset khng i. Cui cng, mt li nn c ni y v cc mask. cvAddS() function dng trong cc code example cho php dng ca mt argument th t m mc nh l NULL: const CvArr*mask=NULL. y l mt 8-bit single-channel array m cho php bn hn ch x l cho mt vng mt n hnh dng bt k nhn dn bi cc nonzero pixel trong mt n. Nu ROI c t cng bi mask, x l s c gii hn vi giao ca ROI v mask. Cc Mask c th c dng ch trong cc functions m ch nh dng chng.

Matrix v Image Operators

Table 3-3 k mt lng cc routine thao tc matrix, hu ht m lm vic tt cho images. Chng lm tt c nhng vic bnh thng, chng hn diagonalizing hay transposing mt matrix, cng nh vi tc v phc tp hn, chng hn tnh thng k image.
Table 3-3. Basic matrix v image operators Function M t cvAbs Tr tuyt i tt c elements trong array cvAbsDiff Tr tuyt i cc khc bit gia hai arrays cvAbsDiffS Tr tuyt i cc khc bit gia array v scalar cvAdd Cng elementwise ca hai array cvAddS Elementwise addition of an array v a scalar cvAddWeighted Elementwise weighted addition of hai arrays (alpha blending) cvAvg Average value of tt c elements in an array cvAvgSdv Absolute value v standard deviation of tt c elements in an array cvCalcCovarMatrix Compute covariance of a set of n-dimensional vectors cvCmp Apply selected comparison operator to tt c elements in hai arrays cvCmpS Apply selected comparison operator to an array relative to a scalar cvConvertScale Convert array type with optional rescaling of the value cvConvertScaleAbs Convert array type sau khi absolute value with optional rescaling

cvCopy cvCountNonZero cvCrossProduct cvCvtColor cvDet cvDiv cvDotProduct cvEigenVV cvFlip cvGEMM cvGetCol cvGetCols cvGetDiag cvGetDims cvGetDimSize cvGetRow cvGetRows cvGetSize cvGetSubRect cvInRange cvInRangeS cvInvert cvMahalonobis cvMax cvMaxS cvMerge cvMin cvMinS cvMinMaxLoc cvMul cvNot cvNorm cvNormalize cvOr cvOrS cvReduce cvRepeat cvSet cvSetZero cvSetIdentity cvSolve

Copy elements of one array to another Count nonzero elements in an array Compute cross product of hai threedimensional vectors Convert channels of an array from one color space to another Compute determinant of a square matrix Elementwise division of one array by another Compute dot product of hai vectors Compute eigenvalues v eigenvectors of a square matrix Flip an array about a selected axis Generalized matrix multiplication Copy elements from column slice of an array Copy elements from multiple adjacent columns of an array Copy elements from an array diagonal Return the number of dimensions of an array Return the sizes of tt c dimensions of an array Copy elements from row slice of an array Copy elements from multiple adjacent rows of an array Get size of a two-dimensional array v return as CvSize Copy elements from subregion of an array Test if elements of an array are with in values of hai other arrays Test if elements of an array are in range gia hai scalars Invert a square matrix Compute Mahalonobis khong cch gia hai vectors Elementwise max operation on hai arrays Elementwise max operation gia an array v a scalar Merge vi single-channel images into one multichannel image Elementwise min operation on hai arrays Elementwise min operation gia an array v a scalar tm thy minimum v maximum values in an array Elementwise multiplication of hai arrays Bitwise inversion of every element of an array Compute normalized correlations gia hai arrays Normalize elements in an array to some value Elementwise bit-level hay of hai arrays Elementwise bit-level hay of an array v a scalar Reduce a two-dimensional array to a vector by a given operation Tile the contents of one array into another Set tt c elements of an array to a given value Set tt c elements of an array to 0 Set tt c elements of an array to 1 for the diagonal v 0 otherwise Solve a system of linear equations

cvSplit cvSub cvSubS cvSubRS cvSum cvSVD cvSVBkSb cvTrace cvTranspose cvXor cvXorS cvZero

Split a multichannel array into multiple singlechannel arrays Elementwise subtraction of one array from another Elementwise subtraction of a scalar from an array Elementwise subtraction of an array from a scalar Sum tt c elements of an array Compute singular value decomposition of a two-dimensional array Compute singular value back-substitution Compute the trace of an array Transpose tt c elements of an array across the diagonal Elementwise bit-level XOR gia hai arrays Elementwise bit-level XOR gia an array v a scalar Set tt c elements of an array to 0

cvAbs, cvAbsDiff, v cvAbsDiffS


void cvAbs( const CvArr* src, const dst ); void cvAbsDiff( const CvArr* src1, const CvArr* src2, const dst ); void cvAbsDiffS( const CvArr* src, CvScalar value, const dst );

Cc function ny tnh tr tuyt i ca array hay khc bit gia array v vi reference. cvAbs() function n gin tnh tr tuyt i ca cc element trong src v vit kt qu vo dst; cvAbsDiff() u tin tr src2 vi src1 v sau vit tr tuyt i hiu vo dst. Lu rng cvAbsDiffS() thc s l ging nh cvAbsDiff() ngoi tr gi tr c tr vi tt c element ca src l gi tr scalar hng.

cvAdd, cvAddS, cvAddWeighted, v alpha blending


void cvAdd( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask = NULL ); void cvAddS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask = NULL ); void cvAddWeighted( const CvArr* src1, double alpha, const CvArr* src2, double beta, double gamma, CvArr* dst );

cvAdd() l function cng n gin: n cng tt c elements trong src1 vi cc element tng ng trong src2 v t cc kt qu vo dst. Nu mask khng t thnh NULL, th

bt k element ca dst m tng ng vi zero element ca mask vn khng i bi tc v ny. Function tng i quen l cvAddS() l iu tng t ngoi tr scalar value hng c thm vo mi element ca src. Function cvAddWeighted() ging vi cvAdd() ngoi tr kt qu vit vo dst c tnh t l theo cng thc sau:

Function ny c th c dng thc hin alpha blending [Smith79; Porter84]; m, n c th c dng trn mt image vi ci khc. Dng ca function ny l:
void cvAddWeighted( const CvArr* src1, double alpha, const CvArr* src2, double beta, double gamma, CvArr* dst );

Trong cvAddWeighted() ta c hai source image, src1 v src2. nhng images ny c th l bt k pixel type v c hai cng type. They c th cng l mt hay ba channels (grayscale hay color), ln na chng phi ging nhau. Image kt qu, dst, phi cng c cng pixel type nh src1 v src2. nhng images ny c th khc nhau size, nhng cc ROI ca chng phi thng nht theo size hay OpenCV s pht ra mt error. Parameter alpha l blending strength ca src1, v beta l blending strength ca src2. Phng trnh alpha blending l: Bn c th chuyn thnh phng trnh alpha blend chun bi chn gia 0 v 1, setting = 1 , v setting thnh 0; iu ny to ra: Tuy nhin, cvAddWeighted() cho ta s linh hot hn c trong cch ta t nng cc blended image v trong parameter ph , m cho php mt additive offset vo image ch. T dng chung, bn s c th mun gi alpha v beta khng nh hn 0 v tng ca chng khng ln hn 1; gamma c th c t ph thuc vo trung bnh hay image value cc i t l cc pixel. Mt program cho thy vic dng alpha blending c thy trong Example 3-14.
Example 3-14. Program hon chnh alpha blend ROI bt u (0,0) trong src2 vi ROI bt u (x,y) trong src1
// alphablend <imageA> <image B> <x> <y> <width> <height> // <alpha> <beta> #include <cv.h> #include <highgui.h> int main(int argc, char** argv) { IplImage *src1, *src2; if( argc == 9 && ((src1=cvLoadImage(argv[1],1)) != 0 )&&((src2=cvLoadImage(argv[2],1)) != 0 )) { int x = atoi(argv[3]); int y = atoi(argv[4]); int width= atoi(argv[5]); int height = atoi(argv[6]); double alpha = (double)atof(argv[7]); double beta = (double)atof(argv[8]); cvSetImageROI(src1, cvRect(x,y,width,height)); cvSetImageROI(src2, cvRect(0,0,width,height)); cvAddWeighted(src1, alpha, src2, beta,0.0,src1); cvResetImageROI(src1); cvNamedWindow( Alpha_blend, 1 ); cvShowImage( Alpha_blend, src1 ); cvWaitKey(); }

Code trong Example 3-14 ly hai source images: ci chnh (src1) v ci blend (src2). N c mt rectangle ROI cho src1 v p dng mt ROI cng size cho src2, ln ny c cp gc. N c alpha v beta levels nhng t gamma thnh 0. Alpha blending c p dng dng cvAddWeighted(), v cc kt qu c t vo src1 v hin th. Example output c thy trong Hnh 3-4, ni mt em b c blend vo mt v ngi ca mo. Lu rng code ly cng ROI nh trong v d cng ROI trong Hnh 3-3. Ln ny ta dng ROI nh vng blending ch.

return 0;

cvAnd v cvAndS

void cvAnd( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask = NULL ); void cvAndS( const CvArr* src1, CvScalar value, CvArr* dst, const CvArr* mask = NULL );

Hai functions ny tnh bitwise v hot ng trn array src1. Trong trng hp ca cvAnd(), mi element ca dst c tnh vi bitwise v vi hai element tng ng ca src1 v src2. Trong trng hp ca cvAndS(), bitwise v c tnh vi scalar value khng i. Nh lun lun, nu mask l khng NULL th ch cc element ca dst tng ng vi cc nonzero entry trong mask c tnh. D tt c data types c h tr, src1 v src2 phi c cng data type cho cvAnd(). Nu cc elements l floating-point type, th biu din bitwise ca floating-point number c dng.

Hnh 3-4. Mt em b c alpha blended vo mt con mo

cvAvg
CvScalar cvAvg(

cvAvg() tnh gi tr trung bnh ca cc pixel trong arr. Nu mask l khc NULL th trung bnh s c tnh trn cc pixel m cho gi tr tng ng ca mask l khc khng. Function ny has the by gi deprecated alias cvMean().

);

const CvArr* arr, const CvArr* mask = NULL

cvAvgSdv

cvAvgSdv( const CvArr* arr, CvScalar* mean, CvScalar* std_dev, const CvArr* mask = NULL );

Function ny ging cvAvg(), nhng thm vo trung bnh n cng tnh vi phn chun ca cc pixel. Function ny by gi mt gi so vi cvMean_StdDev().

cvCalcCovarMatrix

void cvAdd( const CvArr** vects, int count, CvArr* cov_mat, CvArr* avg, int flags );

Cho trc bt k s vector, cvCalcCovarMatrix() s tnh trung bnh v covariance matrix cho xp x Gaussian cho phn phi ca cc im ny. iu ny c th c dng theo nhiu cch, d nhin, v OpenCV c vi flag ph m that s gip c th theo ng cnh (xem Table 3-4). Nhng flags ny c th c kt hp bi vic dng chun ca Boolean hay operator.
Table 3-4. Cc thnh phn c th ca flags argument cho cvCalcCovarMatrix() Flag trong flags ngha argument CV_COVAR_NORMAL Tnh mean v covariance CV_COVAR_SCRAMBLED PCA scrambled covariance nhanh CV_COVAR_USE_AVERAGE Dng avg nh input thay v tnh n CV_COVAR_SCALE Rescale output covariance matrix Trong tt c trng hp, cc vectors c cung cp theo cc vect nh mt array ca

cc OpenCV array (chng hn mt pointer n mt list cc pointer n cc array), vi argument count nhn bit bao nhiu array ang c cung cp. Cc kt qu s c t trong cov_mat trong tt c trng hp, nhng ngha chnh xc ca avg ph thuc vo cc gi tr flag (xem Table 3-4). Cc flags CV_COVAR_NORMAL v CV_COVAR_SCRAMBLED loi tr nhau ; bn nn dng ci ny hay ci kia nhng khng c hai. Trong trng hp ca CV_COVAR_NORMAL, function s n gin tnh mean v covariance cc im c cung cp.

v n c nh ngha nh phn t th n ca average vector v . Covariance matrix kt qu l mt n-by-n matrix. Factor z l mt scale factor ty chn; n s c t thnh 1 tr phi CV_COVAR_SCALE flag c dng. Trong trng hp ca CV_COVAR_SCRAMBLED, cvCalcCovarMatrix() s tnh nh sau:

Matrix ny khng l covariance matrix bnh thng (lu v tr ca transpose operator). Matrix ny c tnh t cng cc m vector chiu di n, nhng scrambled covariance matrix kt qu l mt m-by-m matrix. Matrix ny c dng trong vi thut ton c bit chng hn PCA nhanh cc vector rt ln (nh trong k thut eigenfaces cho face recognition). Flag CV_COVAR_USE_AVG c dng khi mean ca cc input vector hin bit. Trong trng hp ny, argument avg c dng nh input hn mt output, m gim thi gian tnh ton. Cui cng, flag CV_COVAR_SCALE c dng p uniform scale cho covariance matrix c tnh. y l factor z trong cc phng trnh trc. Khi c dng kt hp vi CV_COVAR_NORMAL flag, scale factor c p s l 1.0/m (hay, tng ng, 1.0/ count). Nu thay v CV_COVAR_SCRAMBLED c dng, th gi tr z s l 1.0/n (nghch o chiu di cc vector). Cc input v output array cho cvCalcCovarMatrix() nn tt c l cng floating-point type. Size ca matrix cov_mat kt qu s l mt trong n-by-n hay m-by-m ph thuc vo c hay khng covariance chun hay scrambled ang c tnh. nn c lu rng cc vectors input trong vects khng thc s phi l mt chiu; chng c th l cc two-dimensional object (chng hn cc image).

cvCmp v cvCmpS

C hai function ny lm cc so snh, mt trong gia pixels tng ng trong hai images hay gia pixels trong mt image v mt scalar value khng i. C cvCmp() v cvCmpS() ly argument cui ca chng l mt comparison operator, m c th l bt k types k trong Table 3-5.
Table 3-5. Cc gi tr ca cmp_op c dng bi cvCmp() v cvCmpS() v comparison operation kt qu c thc hin Value of Comparison cmp_op
CV_CMP_EQ CV_CMP_GT CV_CMP_GE CV_CMP_LT CV_CMP_LE CV_CMP_NE (src1i src2i) (src1i (src1i src2i) (src1i (src1i src2i) (src1i == > src2i) >= < src2i) <= != src2i)

void cvCmp( const CvArr* src1, const CvArr* src2, CvArr* dst, int cmp_op ); void cvCmpS( const CvArr* src, double value, CvArr* dst, int cmp_op );

Tt c so snh c k c lm vi cng cc function; bn ch chuyn vo argument thch hp nhn din ci bn mun lm. Nhng functions c th ny lm vic ch trn cc single-channel image. Cc function so snh ny hai ch trong cc application ni bn lm vi phin bn ca background subtraction v mun mask cc kt qu (chng hn quan st video stream t mt security camera) m ch nhng thng tin mi c y ra khi image.

cvConvertScale
void cvConvertScale( const CvArr* src, CvArr* dst, double scale = 1.0, double shift= 0.0

);

cvConvertScale() function thc s l vi function c gom thnh mt ci; ms s thc

hin bt k trong vi functions hay, nu cn, tt c chng cng nhau. Function u tin l chuyn data type trong source image thnh data type ca destination image. V d, nu ta have mt 8-bit RGB grayscale image v m mun chuyn thnh 16-bit signed image, ta c th lm bi gi cvConvertScale(). Function th hai ca cvConvertScale() l thc hin bin i tuyn tnh trn image data. Sau khi chuyn thnh data type mi, mi pixel value s c nhn bi value scale v sau cng n vo value shift. iu quan trng phi nh, ngay c qua Convert i trc Scale trong function name, th t thc m trong nhng operations ny c thc hin l ngc li. c bit, vic nhn bi scale v cng shift xy ra trc khi chuyn type c lm. Khi bn n gin chuyn cc value mc nh (scale = 1.0 v shift= 0.0), bn khng cn c cc s hi hiu sut; OpenCV thng minh nhn bit trng hp ny v khng lng ph processor time cho cc tc v v ch. r rng (nu bn ngh n cng ty ), OpenCV cng cung cp macro cvConvert(), m l ging nh cvConvertScale() nhng c dng theo thi quen khi cc tham s scale v shift s c gi tr mc nh ca chng. cvConvertScale() s lm vic trn tt c data types v bt k s channel, nhng s channel trong source v destination images phi ging nhau. (nu bn mun chuyn t color thnh grayscale hay ngc li, xem cvCvtColor(), m n ngay sau.)

cvConvertScaleAbs

cvConvertScaleAbs() thc s l ng cho cvConvertScale() ngoi tr rng dst image cha gi tr tuyt i ca data kt qu. c bit, cvConvertScaleAbs() cc scales v shifts u tin, sau tnh gi tr tuyt i, v cui cng thc hin chuyn datatype.

void cvConvertScaleAbs( const CvArr* src, CvArr* dst, double scale = 1.0, double shift= 0.0 );

cvCopy

void cvCopy( const CvArr* src, CvArr* dst, const CvArr* mask = NULL );

y l cch bn copy mt image thnh ci khc. cvCopy() function mong c hai array phi c cng kiu, cng size, v cng s cc dimension. Bn c th dng n copy cc array tha, nhng cho iu ny vic dng ca mask khng c h tr. Cho cc arrays khng tha v images, hiu ng ca mask (nu khc NULL) ch l cc pixels trong dst m tng ng vi cc entry khc khng trong mask s c thay i.

cvCountNonZero cvCrossProduct

cvCountNonZero() tr v s cc pixel khc khng trong array arr.


void cvCrossProduct( const CvArr* src1, const CvArr* src2, CvArr* dst );

int cvCountNonZero( const CvArr* arr );

Function ny tnh vector cross product [Lagrange1773] ca hai three-dimensional vectors. N khng quan tm cc vectors dng hng hay ct (mt t phn x tit l rng, cho cc single-channel objects, hai ci ny thc s l ging nhau bn trong). C src1 v src2 nn l cc single-channel arrays, v dst s l single-channel v chiu di chnh xc l 3.Tt c ba arrays s l ca cng data type.

cvCvtColor

void cvCvtColor( const CvArr* src,

Cc function trc l chuyn t mt data type thnh ci khc, v chng mun s cc channel l ging nhau trong c cc source v destination image. Function hon chnh l cvCvtColor(), m chuyn t mt color space (number of channels) thnh mt ci khc [Wharton71] trong khi mun data type l ging nhau. Tc v chuyn i chnh xc c lm c ch nh bi argument code, m cc gi tr c th c k trong Table 3-6.*
Table 3-6. Conversions available by means of cvCvtColor() Conversion code Meaning CV_BGR2RGB Chuyn gia RGB v BGR color spaces CV_RGB2BGR (c hay khng c alpha channel)
CV_RGBA2BGRA CV_BGRA2RGBA CV_RGB2RGBA CV_BGR2BGRA CV_RGBA2RGB CV_BGRA2BGR CV_RGB2BGRA CV_RGBA2BGR CV_BGRA2RGB CV_BGR2RGBA CV_RGB2GRAY CV_BGR2GRAY CV_GRAY2RGB CV_GRAY2BGR CV_RGBA2GRAY CV_BGRA2GRAY CV_GRAY2RGBA CV_GRAY2BGRA CV_RGB2BGR565 CV_BGR2BGR565 CV_BGR5652RGB CV_BGR5652BGR CV_RGBA2BGR565 CV_BGRA2BGR565 CV_BGR5652RGBA CV_BGR5652BGRA CV_GRAY2BGR565 CV_BGR5652GRAY CV_RGB2BGR555 CV_BGR2BGR555 CV_BGR5552RGB CV_BGR5552BGR CV_RGBA2BGR555 CV_BGRA2BGR555 CV_BGR5552RGBA CV_BGR5552BGRA CV_GRAY2BGR555 CV_BGR5552GRAY CV_RGB2XYZ CV_BGR2XYZ CV_XYZ2RGB CV_XYZ2BGR CV_RGB2YCrCb CV_BGR2YCrCb CV_YCrCb2RGB CV_YCrCb2BGR

);

CvArr* dst, int code

Thm alpha channel vo RGB hay BGR image Xa alpha channel khi RGB hay BGR image Chuyn RGB thnh BGR color spaces trong khi thm hay xa alpha channel Chuyn RGB hay BGR color spaces thnh grayscale Chuyn grayscale thnh RGB hay BGR color spaces (ty chn xa alpha channel trong x l) Convert grayscale to RGB hay BGR color spaces v add alpha channel Convert from RGB hay BGR color space to BGR565 color representation with optional addition hay removal of alpha channel (16-bit images)

Convert grayscale to BGR565 color representation hay vice versa (16-bit images) Convert from RGB hay BGR color space to BGR555 color representation with optional addition hay removal of alpha channel (16-bit images)

Convert grayscale to BGR555 color representation hay vice versa (16-bit images) Convert RGB hay BGR image to CIE XYZ representation hay vice versa (Rec 709 with D65 white point) Convert RGB hay BGR image to lumachroma (aka YCC) color representation

CV_RGB2HSV CV_BGR2HSV CV_HSV2RGB CV_HSV2BGR CV_RGB2HLS CV_BGR2HLS CV_HLS2RGB CV_HLS2BGR CV_RGB2Lab CV_BGR2Lab CV_Lab2RGB CV_Lab2BGR CV_RGB2Luv CV_BGR2Luv CV_Luv2RGB CV_Luv2BGR CV_BayerBG2RGB CV_BayerGB2RGB CV_BayerRG2RGB CV_BayerGR2RGB CV_BayerBG2BGR CV_BayerGB2BGR CV_BayerRG2BGR CV_BayerGR2BGR

Convert RGB hay BGR image to HSV (hue saturation value) color representation or vice versa Convert RGB hay BGR image to HLS (hue lightness saturation) color representation or vice versa Convert RGB hay BGR image to CIE Lab color representation hay vice versa Convert RGB hay BGR image to CIE Luv color representation Convert from Bayer pattern (singlechannel) to RGB hay BGR image

Cc chi tit ca nhiu trong nhng chuyn i ny l quan trng, v ta s khng i vo ch ca biu din Bayer ca cc CIE color spaces y. Cho cc mc ch ca ta, l lu rng OpenCV cha cc tool chuyn thnh v t nhng color space khc nhau, m l quan trng vi cc lp khc nhau ngi dng. Chuyn i color-space tt c dng cc chuyn i: 8-bit images trong di 0255, 16-bit images trong di 065536, v cc s floating-point trong di 0.01.0. Khi grayscale images c chuyn thnh color images, tt c cc thnh phn ca image kt qu c ly l bng; nhng cho bin i ngc (chng hn RGB hay BGR thnh grayscale), gray value c tnh bi dng cng thc trng s cm gic sau: Y=(0.299)R+(0.587)G+(0.114)B Trong trng hp ca biu din HSV hay HLS, hue thng thng c biu din nh value t 0 n 360.* iu ny c th gy ra rc ri trong cc biu din 8-bit v do , khi chuyn thnh HSV, hue c chia bi 2 khi output image l mt 8-bit image.

cvDet

cvDet() tnh determinant (Det) crr mt array vung. Array c th l bt k data type,

double cvDet( const CvArr* mat );

nhng n phi l single-channel. Nu matrix l nh th determinant trc tip c tnh bi cng thc chun. Cho cc cc matrix ln, iu ny c bit khng hiu qu v do determinant c tnh bi Gaussian elimination. Nu ng bit bn hin bit rng mt matrix l i xng v c mt determinant dng, bn c th cng dng mo gii qua singular value decomposition (SVD). Cho nhiu thng tin hn xem Phn cvSVD theo sau, nhng mo l t c U v V thnh NULL v sau ly cc product ca matrix W ly determinant.

cvDiv

cvDiv() l function chia n gin; n chia tt c elements trong src1 bi cc elements tng ng trong src2 v t cc kt qu vo dst. Nu mask l khc NULL, th bt k element ca dst m tng ng vi mt zero element ca mask khng c thay i bi

void cvDiv( const CvArr* src1, const CvArr* src2, CvArr* dst, double scale = 1 );

operation ny. Nu bn ch mun nghch o tt c elements trong mt array, bn c

th chuyn NULL v tr ca src1; routine s lm vic vi iu ny nh mt array ca ci s mt.

cvDotProduct

Function ny tnh vector dot product [Lagrange1773] ca hai N-dimensional vectors.* Nh vi cross product (v cho cng nguyn nhn), n khng g nu cc vector dng hng hay ct. C src1 v src2 nn l cc single-channel arrays, v c hai array nn l cng kiu data.

double cvDotProduct( const CvArr* src1, const CvArr* src2 );

cvEigenVV

Cho trc mt matrix i xng mat, cvEigenVV() s tnh eigenvectors v eigenvalues tng ng ca matrix . iu ny c lm dng Jacobis method [Bronshtein97], do n hiu qu cho cc matrix nh hn. Jacobis method i hi mt stopping parameter, m l kch thc cc i ca cc off-diagonal elements trong matrix cui. Optional argument eps t gi tr kt thc. Trong tin trnh ca tnh ton, matrix c cung cp mat c dng tnh, do cc value ca n s b thay i bi function. Khi function returns, bn s tm thy cc eigenvector ca bn trong evects dng ca cc hng tip theo. Cc gi tr eigen tng ng c lu trong evals. Th t cc eigenvector s lun lun l ngc theo bin ca cc eigenvalues tng ng. cvEigenVV() function i hi tt c ba arrays cho floating-point type. Nh vi cvDet() (m t trc y), nu matrix ang yu cu c bit l i xng v positive definite th tt hn l dng SVD tm eigenvalues v eigenvectors ca mat.

double cvEigenVV( CvArr* mat, CvArr* evects, CvArr* evals, double eps = 0 );

cvFlip

void cvFlip( const CvArr* src, CvArr* dst = NULL, int flip_mode = 0 );

Function ny lp mt image quanh x-axis, the y-axis, hay c hai. V c th, nu argument flip_mode c t thnh 0 th image s c lp quanh x-axis. Nu flip_mode c t tnh mt gi tr dng (chng hn +1) image s c lp quanh yaxis, v nu t thnh m (chng hn 1) image s c lt c hai trc. Khi x l video trn cc Win32 systems, bn s t tm thy vic dng function ny thng chuyn gia cc image format viis gc ca chng upper-left v lower-left ca image.

cvGEMM

Generalized matrix multiplication (GEMM) trong OpenCV c thc hin bi cvGEMM(), m thc hin nhn matrix, nhn bi mt transpose, scaled multiplication, et cetera. Trong dng chun hu ht ca n, cvGEMM() tnh nh sau:

double cvGEMM( const CvArr* src1, const CvArr* src2, double alpha, const CvArr* src3, double beta, CvArr* dst, int tABC = 0 );

Trong A, B, v C l (tng ng) cc matrix src1, src2, v src3, v l cc h s, v op() l mt transposition ty chn ca matrix bao quanh. Argument src3 c th c t thnh NULL, m trong trng hp n s khng c cng. Cc transpositions c khin bi optional argument tABC, m c th l 0 hay bt k s kt hp (bi cc phng tin ca Boolean OR) ca CV_GEMM_A_T, CV_GEMM_B_T, v CV_GEMM_C_T (vi mi flag nhn din mt transposition ca matrix tng ng). Trong qu kh xa OpenCV cha cc methods cvMatMul() v cvMatMulAdd(), nhng nhng ci ny thng qu ln xn vi cvMul(), m m g khc hon ton (chng hn nhn phn t vi phn t ca hai array). nhng functions ny tip tc tn ti nh cc macro cho cc li gi n cvGEMM(). V c th, ta c hai tng ng k trong Table 3-7.
Table 3-7. Macro aliases for common usages of cvGEMM()
cvMatMul(A, B, D) cvMatMulAdd(A, B, C, D) cvGEMM(A, A, 1, NULL, 0, D, 0) cvGEMM(A, A, 1, C, 1, D, 0)

Tt c cc matrix phi size thch hp nhn, v tt c nn l kiu floating-point. cvGEMM() function h tr cc matrix two-channel, m trong trng hp n s lm hai channels nh hai components ca mt single complex number.

cvGetCol v cvGetCols

Function cvGetCol() c dng lyys mt column n ra khi mt matrix v return n nh mt vector (chng hn nh mt matrix vi ch mt column). Trong trng hp ny matrix header submat s c bin i tr n mt column c th trong arr. iu quan trng cn lu rng bin i header nh th khng include allocation of memory hay copying ca data. Ni dung ca submat s n gin c thay i sao cho n nhn bit ng column c chn trong arr. Tt c data types c h tr. cvGetCols() lm vic chnh xc theo cng cch , ngoi tr rng tt c columns t start_col n end_col c chn. Vi c hai function, return value l mt pointer n mt header tng ng vi column hay column span c ch inh c th (chng hn submat) c chn bi trnh gi.

CvMat* cvGetCol( const CvArr* arr, CvMat* submat, int col ); CvMat* cvGetCols( const CvArr* arr, CvMat* submat, int start_col, int end_col );

cvGetDiag

cvGetDiag() tng tj vi cvGetCol(); n c dng ly mt single diagonal t mt matrix v return n nh mt vector. Argument submat l mt matrix header. Function cvGetDiag() s in cc component ca header ny sao cho n tr n thng tin ng trong arr. Lu rng kt qu ca gi cvGetDiag() m l header bn cung cp l c cu hnh ng tr nns diagonal data trong arr, nhng data t arr khng c copy. Optional argument diag ch nh diagonal m c tr n bi submat. Nu diag c t thnh default value 0, diagonal chnh s c chn. Nu diag ln hn 0, th diagonal bt u (diag,0) s c chn; nu diag nh hn 0, th diagonal bt u (0,-diag) s c chn thay. cvGetDiag() function khng i hi matrix arr l vung, nhng array submat phi c chiu di ng cho size ca input array. Returned value cui l ging nh value ca submat chuyn vo khi the function c gi.

CvMat* cvGetDiag( const CvArr* arr, CvMat* submat, int diag = 0 );

cvGetDims v cvGetDimSize

Nh rn cc arrays trong OpenCV c th c chiu ln hn hai. Function cvGetDims() tr v s cc chiu array ca mt array c th v (optionally) cc size ca mi dimension ny. Cc size s c bo co nu cc array size l khng NULL. Nu sizes c dng, n nn l mt mt pointer n n integers, trong n l s cc dimension. Nu bn khng bit s dimension trc, bn c th cp cc sizes cho CV_MAX_DIM integers ch an ton. Function cvGetDimSize() tr v size ca dimension n c ch nh bi index. Nu array l mt trong mt matrix hay mt image, s cc dimension c return s lun lun l hai.* Cho cc cc matrix v images, th t ca size tr v bi cvGetDims() s lun lun l s cc hng u tin theo sau bi s cc ct.

int cvGetDims( const CvArr* arr, int* sizes=NULL ); int cvGetDimSize( const CvArr* arr, int index );

cvGetRow v cvGetRows
CvMat* cvGetRow( const CvArr* arr, CvMat* submat, int row ); CvMat* cvGetRows( const CvArr* arr, CvMat* submat, int start_row, int end_row );

cvGetRow() ly mt single row ra khi mt matrix v tr v n nh mt vector (mt matrix vi ch mt hng). Nh vi cvGetRow(),matrix header submat s c bin i thnh tr n mt hng c th trong arr, v cc bin i ca header ny khng bao gm vic cp memory hay copying data; ni dung ca submat s n gin c thay i nh n nhn bit ng ct c chn trong arr. Tt c data types c h tr. Function cvGetRows() lm vic chnh xc ging cch, ngoi tr rng tt c cc hng t start_row n end_row c chn. Ci c hai function, return value l mt pointer n

mt header tng ng vi hng hay row span ch nh c th chn bi trnh gi.

cvGetSize

CvSize cvGetSize( const CvArr* arr );

Lin quan gn vi cvGetDims(), cvGetSize() tr v size ca mt array. Khc bit chnh l cvGetSize() c thit k c dng trn cc matrix v images, m lun lun c dimension l hai. Size c th sau c tr v theo dng ca mt CvSize structure, m ph hp dng khi (v d) xy dng matrix hay image mi ca cng size.

cvGetSubRect

cvGetSubRect() l tng t vi cvGetColumns() hay cvGetRows() ngoi tr rng n chn vi hnh ch nht con ty trong array ch nh bi argument rect. Nh vi cc routine khc m chn cc phn ph ca cc array, submat n gin l mt header m s c in bi cvGetSubRect() theo mt cch m n tr ng n submatrix mong

CvSize cvGetSubRect( const CvArr* arr, CvArr* submat, CvRect rect );

mun (chng hn khng c memory c cp v khng data c copy).

cvInRange v cvInRangeS
void cvInRange( const CvArr* src, const CvArr* lower, const CvArr* upper, CvArr* dst

Hai functions ny c th c dng kim tra c cc pixels trong mt image ri vo mt di c ch nh c th. Trong trng hp ca cvInRange(), mi pixel ca src c so vi value tng ng trong cc images lower v upper. Nu value trong src l ln hn hay bng value trong lower v cng nh hn value trong upper, sau value tng ng trong dst s c t thnh 0xff; ngc li, value trong dst s c t thnh 0. Function cvInRangeS() lm vic chnh xc cng cch ngoi tr rng image src c so vi cc gi tr hng (CvScalar) theo lower v upper. Cho c hai function, image src c th l bt k type; nu n c nhiu channels th mi channel s c handle ring. Lu rng dst phi l cng size v s channels v cng phi mt 8-bit image.

); void cvInRangeS( const CvArr* src, CvScalar lower, CvScalar upper, CvArr* dst );

cvInvert

cvInvert() nghch o matrix trong src v t kt qu trong dst. Function ny h tr vi

double cvInvert( const CvArr* src, CvArr* dst, Int method = CV_LU );

methods ca tnh inverse matrix (xem Table 3-8), nhng mc nh l Gaussian elimination. Return value ph thuc vo method c dng.

Table 3-8. Possible values of method argument to cvInvert() Value of method Meaning argument CV_LU Gaussian elimination (LU Decomposition) CV_SVD Singular value decomposition (SVD) CV_SVD_SYM SVD for symmetric cc matrix Trong trng hp ca Gaussian elimination (method=CV_LU), determinant ca src c

tr v khi function hon thnh. Nu determinant l 0, th nghch o khng thc s c thc hin v array dst n gin c t tt c thnh 0. Trong trng hp ca CV_SVD hay CV_SVD_SYM, return value l s iu kin nghch o cho matrix (ratio ca eigenvalue nh nht n ln nht). Nu matrix src l singular, th cvInvert() trong SVD mode s thay vo tnh pseudo-inverse.

cvMahalonobis

CvSize cvMahalonobis( const CvArr* vec1, const CvArr* vec2, CvArr* mat );

Khong cch Mahalonobis (Mahal) c nh ngha nh vector khong cch o gia mt im v tm ca phn phi Gaussian ; n c tnh dng inverse covariance m phn phi nh mt metric. Xem Figure 3-5. V trc gic, iu ny tng t vi zscore trong thng k c bn, trong khong cch t tm ca phn phi c o theo n v thay i ca phn phi . Khong cch Mahalonobis ch l tng qut ha a bin ca cng tng. cvMahalonobis() tnh gi tr ny:

rMahalonobis = ( x )T ( x )
1

Vector vec1 c cng trc l im x, v vector vec2 c ly l hiu dng ca phn phi.* Matrix mat l inverse covariance. Trong thc t, covariance matrix ny s thng c tnh bng cvCalcCovar Matrix() (c m t trc y) v sau nghch o bng cvInvert(). Thc t lp trnh tt l dng SV_SVD method cho nghch o ny v mt ngy bn s trm chn mt phn phi m l mt trong cc eigenvalue l 0!

cvMax v cvMaxS
void cvMax( const CvArr* src1, const CvArr* src2, ); void cvMaxS( const CvArr* src, double value, CvArr* dst );

Hnh 3-5. Mt phn phi cc im trong hai chiu vi cc ellipsoids xp chng biu din khong cch Mahalonobis ca 1.0, 2.0, v 3.0 t hiu dng ca phn phi cvMax() tnh gi tr cc i ca cp tng ng cc pixel trong cc array src1 v src2. Vi cvMaxS(), src array c so vi scalar value hng. Nh lun lun, nu mask l khc NULL th ch cc element ca dst tng ng vi cc entry khc khng trong mask c

tnh.

cvMerge
void cvMerge( const CvArr* const CvArr* const CvArr* const CvArr* CvArr* dst ); src0, src1, src2, src3,

cvMerge() l tc v nghch o ca cvSplit() . Arrays trong src0, src1, src2, v src3 c kt hp vo array dst. D nhin, dst nn c cng data type v size nh tt c trong cc

source array, nhng c th c hai, ba, hay bn channel. Cc source image khng c dng c th c leftset thnh NULL.

cvMin v cvMinS

void cvMin( const CvArr* src1, const CvArr* src2, CvArr* dst ); void cvMinS( const CvArr* src,

cvMin() tnh gi tr cc tiu mi cp tng ng ca cc pixels trong arrays src1 v src2. Vi cvMinS(), cc src arrays c so vi scalar value hng. Ln na, nu mask khc NULL th ch cc elements ca dst tng ng vi cc entry khc khng trong mask c tnh.

);

double value, CvArr* dst

cvMinMaxLoc

void cvMinMaxLoc( const CvArr* arr, double* min_val, double* max_val, CvPoint* min_loc = NULL, CvPoint* max_loc = NULL, const CvArr* mask = NULL );

Routine ny tm cc gi tr c i v cc tiu trong array arr v (ty chn) tr v v tr ca chng. Cc gi tr cc i v cc tiu c tnh c t trong min_val v max_val. Ty chn, cc v tr ca cc cc tr ny s cng c vit vo cc a ch cho bi min_loc v max_loc nu cc ha tr ny l khng NULL. Nh bnh thng, nu mask l khc NULL v ch cc phn ca image arr m tng ng vi cc nonzero pixels trong mask c quan tm. cvMinMaxLoc() routine handles ch single-channel arrays, tuy nhin, do nu bn c mt multichannel array th bn nn dng cvSetCOI() set mt channel c th quan tm.

cvMul

void cvMul( const CvArr* src1, const CvArr* src2, CvArr* dst, double scale=1 );

cvMul() l multiplication function n gin. N nhn tt c cc elements trong src1 bi cc elements tng ng trong src2 v sau t cc kt qu trong dst. Nu mask l non-NULL, th bt k element ca dst m tng ng vi mt zero element ca mask khng c thay i bi operation ny. Khng c function cvMulS() v chc nng hin c cp bi cvScale() hay cvCvtScale(). Mt iu xa hn cn nh: cvMul() thc hin nhn phn t vi phn t. Mt ngy, khi bn ang nhn vi matrix, bn c th b li cun n vi cvMul(). iu ny s lm vic; nh rng nhn matrix c lm vi cvGEMM(), khng vi cvMul().

cvNot

void( );

const CvArr* src, CvArr* dst

Function cvNot() nghch o mi bit trong mi element ca src v sau t kt qu trong dst. Do , cho mt 8-bit image value 0x00 s c nh x thnh 0xff v value 0x83 s c chiu thnh 0x7c.

cvNorm

Function ny c th c dng tnh total norm ca mt array v cng mt lng cc norm khong cch tng i nu hai arrays c cung cp. Trong trng hp trc, norm c tnh nh c thy trong Table 3-9.
Table 3-9. Norm c tnh bi cvNorm() cho cc gi tr khc nhau ca khi arr2=NULL

double cvNorm( const CvArr* arr1, const CvArr* arr2 = NULL, int norm_type = CV_L2, const CvArr* mask = NULL );

Norm_typ e CV_C

Kt qu

|| arr1 ||c = max x , y abs ( arr1x , y )

CV_L1 CV_L2

|| arr1 || L1 = abs ( arr1x , y )


x, y

|| arr1 || L 2 = arr12 x, y )
x, y

Nu array argument th hai arr2 l non-NULL, th norm c tnh l mt norm khc m l, g ging khong cch gia hai arrays.* Trong ba trng hp u tin c thy trong Table 3-10, norm l tuyt i; trong hai trng hp sau n c rescale bi bin ca array th hai arr2.
Table 3-10. Norm c tnh bi cvNorm() cho cc gi tr khc nhau ca norm_type khi arr2 l non-NULL

Norm_type CV_C CV_L1 CV_L2 CV_RELATIVE_C CV_RELATIVE_L1

Kt qu || arr1 arr 2 ||c = max x , y abs ( arr1x , y arr 2 x , y )

|| arr1 arr 2 || L1 = abs ( arr1x , y arr 2 x , y )


x, y

|| arr1 arr 2 || x , y = ( arr1x , y arr 2 x , y ) 2


x, y

|| arr1 arr 2 ||C || arr 2 ||C || arr1 arr 2 || L1 || arr 2 ||L 2

Trong tt c trng hp, arr1 v arr2 phi c cng size v s channel. Khi c nhiu hn mt channel, norm c tnh trn tt c cc channel cng nhau (chng hn cc sum trong Tables 3-9 v 3-10 l khng ch trn x v y m cn trn cc channel).

cvNormalize

Nh vi nhiu OpenCV function, cvNormalize() lm nhiu hn n c th u tin xut hin. Ph thuc vo value ca norm_type, image src c normalized hay ngc li c chiu vo di c th trong dst. Cc gi tr c th ca norm_type c thy trong Table 3-11.
Table 3-11. Cc gi tr c th ca norm_type argument cho cvNormalize()

cvNormalize( const CvArr* src, CvArr* dst, double a = 1.0, double b = 0.0, int norm_type = CV_L2, const CvArr* mask = NULL );

Norm_type CV_C CV_L1 CV_L2 CV_MINMAX

Kt qu || arr1 ||C = max dst abs ( I x , y ) = a

|| arr1 || L1 = abs ( I x , y ) = a
2 || arr1 || L 2 = I x ,y = a dst
dst

Chiu vo di [a,b]

Trong trng hp ca C norm, array src c rescaled thnh bin ca gi tr tuyt i ca entry ln nht bng vi a. Trong trng hp L1 hay L2 norm, array c rescaled sao cho norm c cho bng vi gi tr ca a. Nu norm_type c t thnh CV_MINMAX, th cc gi tr ca array c rescaled v translated sao cho chng c chiu tuyn tnh vo khong gia a v b (bao gm).

Nh trc, nu mask l non-NULL th ch cc pixels m tng ng vi cc nonzero values ca mask image s cu thnh tnh ton ca normv ch cc pixels ny s c thay i bi cvNormalize().

cvOr v cvOrS

void cvOr( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL ); void cvOrS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask = NULL );

Hai functions ny tnh bitwise OR operation trn array src1. Trong trng hp ca cvOr(), mi element ca dst c tnh nh bitwise OR ca hai elements tng ng ca src1 v src2. Trong trng hp ca cvOrS(), bitwise OR c tnh vi scalar value hng. Nh thng, nu mask l non-NULL th ch cc elements ca dst tng ng vi cc nonzero entry trong mask c tnh. Tt ca data types c h tr, nhng src1 v src2 phi c cng data type cho cvOr(). Nu cc elements l floating-point type, th biu din bitwise ca floating-point number c dng.

cvReduce

CvSize cvReduce( const CvArr* src, CvArr* dst, int dim, int op = CV_REDUCE_SUM );

Reduction l bin i systematic ca input matrix src vo mt vector dst bi p dng vi lut kt hp op trn mi hng (hay ct) v lng gingf ca n n khi ch mt hng (hay ct) vn th (xem Table 3-12).* Argument op iu khin cch reduction c lm, nh tng kt trong Table 3-13.

Table 3-12. Argument op trong cvReduce() chn reduction operator Value of op Result CV_REDUCE_SUM Compute sum across vectors CV_REDUCE_AVG Compute average across vectors CV_REDUCE_MAX Compute maximum across vectors CV_REDUCE_MIN Compute minimum across vectors Table 3-13. Argument dim trong cvReduce() iu khin hng ca reduction Value of dim Result +1 Collapse to a single row 0 Collapse to a single column 1 Collapse as appropriate for dst cvReduce() h tr multichannel arrays ca floating-point type. N cng cho php dng mt precision type cao hn trong dst hn xut hin trong src. iu ny thch hp chnh cho CV_REDUCE_SUM v CV_REDUCE_AVG, ni overflows v cc vn cng l c

th.

cvRepeat

void cvRepeat( const CvArr* src, CvArr* dst );

Function ny chp ni dung ca src vo dst, lp li bao nhiu ln nh cn thit in dst. V c th, dst c th l bt k size tng ng vi src. N c th l ln hn hay

nh hn, v n khng cn c mt s nguyn quan h gia bt k cc chiu ca n v cc chiu tng ng ca src.

cvScale

Function cvScale() thc s l mt macro cho cvConvertScale() m t shift argument thnh 0.0. Do , n c th c dng rescale ni dung ca mt array v chuyn t mt kiu ca data type thnh kiu khc.

void cvScale( const CvArr* src, CvArr* dst, double scale );

cvSet v cvSetZero

void cvSet( CvArr* arr, CvScalar value, const CvArr* mask = NULL );

Cc function ny set tt c values trong tt c channel ca array thnh gi tr c th. cvSet() function nhn mt mask argument ty chn: nu mask c cung cp, th ch cc pixels ny trong image arr m tng ng vi cc nonzero values ca mask image s c t thnh value ch nh. Function cvSetZero() ch l mt ng ngha cho cvSet(0.0).

cvSetIdentity

cvSetIdentity() t tt c elements ca array thnh 0 ngoi tr cho cc element m hng v ct l bng; cc elements ny c t thnh 1. cvSetIdentity() h tr tt c

void cvSetIdentity( CvArr* arr );

data types v khng ngay c i hi array l vung.

cvSolve

int cvSolve( const CvArr* src1, const CvArr* src2, CvArr* dst, int method = CV_LU );

Function cvSolve() cung cp mt cch nhanh gii cc h tuyn tnh da trn cvInvert(). N tnh li gii vi

C = arg min x || A. X B ||

Trong A l square matrix cho bi src1, B l vector src2, v C l li gii tnh bi cvSolve() cho vector tt nht X n c th tm thy. Vector tt nht X c tr v trong dst. Cng cc method c h tr nh bi cvInvert() (m t trc y); ch cc floating-point data type c h tr. Function tr v mt integer value trong mt nonzero return nhn bit m n c th tm thy mt p n. Nn c lu rng cvSolve() c th c dng gii overdetermined cc h tuyn tnh. Overdetermined systems s c gii dng g gi l pseudo-inverse, m dng cc SVD method tm thy p n least-squares cho h phng trnh.

cvSplit

C cc ln khi khng thun li lm vic vi mt multichannel image. Trong cc trng hp ny, ta c th dng cvSplit() copy mi channel ring thnh mt trrg vi single-channel images c cung cp. cvSplit() function s copy cc channels trong src vo images dst0, dst1, dst2, v dst3 nh cn thit. Cc destination images phi tha mn source image theo size v data type nhng, d nhin, nn l cc single-

void cvSplit( const CvArr* src, CvArr* dst0, CvArr* dst1, CvArr* dst2, CvArr* dst3 );

channel images. Nu source image c t hn bn channels (nh n s thng), th cc destination argument khng cn thit cho cvSplit() c th c t thnh NULL.

cvSub

Function ny thc hin mt php tr phn t phn t c s ca mt array src2 vi mt ci khc src1 v t kt qu trong dst. Nu array mask l non-NULL, th ch cc elements ny ca dst tng ng vi cc nonzero elements ca mask c tnh. Lu rng src1, src2, v dst phi tt c c cng type, size, v s cc channels; mask, nu c dng, nn l mt 8-bit array ca cng size v s cc channels nh dst.

void cvSub( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask = NULL );

cvSub, cvSubS, v cvSubRS

void cvSub( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask = NULL ); void cvSubS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask = NULL ); void cvSubRS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask = NULL );

cvSub() l mt hm tr n gin; n tr tt c cc elements trong src2 vi cc elements tng ng trong src1 v t cc kt qu trong dst. Nu mask l non-NULL, th bt k element ca dst m tng ng vi mt zero element ca mask khng c thay i bi tc v ny. Function lin quan gn cvSubS() lm cng vic ngoi tr rng mt constant scalar value c thm cho mi element ca src. Function cvSubRS() l ging nh cvSubS() ngoi tr rng, hn vic tr mt hng vi mi element ca src, n tr mi element ca src vi value hng.

cvSum

cvSum() cng tt c pixels trong tt c cc channels ca array arr. Nhn thy rng return value l kiu CvScalar, m c ngha rng cvSum() c th thch hp cc

CvScalar cvSum( CvArr* arr );

multichannel arrays. Trong trng hp , tng ca mi channel c t trong thnh phn tng ng ca CvScalar return value.

cvSVD

Singular value decomposition (SVD) l phn r ca mt m-by-m matrix A thnh dng: Trong W is a diagonal matrix v U v V l cc matrix hp nht m-by-m v n-by-n. D nhin matrix W cng l m-by-n matrix, do y diagonal c ngha rng bt k element m s hng v cottj l khng bng nhau th nht thit bng 0. V W nht

void cvSVD( CvArr* A, CvArr* W, CvArr* U = NULL, CvArr* V = NULL, int flags = 0 );

A = U W V T

thit l diagonal, OpenCV cho php n c biu din mt trong bi mt m-by-n matrix hay bi mt n-by-1 vector (m trong trng hp vector s cha ch cc gi tr diagonal singular). Cc matrix U v V l ty chn vi cvSVD(), v nu chng c t thnh NULL th khng c gi tr s c tr v. Cc argument flags cui c th l bt k hay tt c trong ba option c m t trong Table 3-14 (c kt hp nh thch hp bng Boolean hay operator).
Table 3-14. Cc flag c th cho flags argument vi cvSVD() Flag Result CV_SVD_MODIFY_A cho php modification of matrix A CV_SVD_U_T Return UT thay v U CV_SVD_V_T Return VT thay v V

cvSVBkSb

void cvSVBkSb( const CvArr* const CvArr* const CvArr* const CvArr* CvArr* X, int flags = 0 );

W, U, V, B,

y l mt function m bn khng thch gi trc tip. Trong kt hp vi cvSVD() (va c m t), n nm di cc SVD-based methods ca cvInvert() v cvSolve(). M c bo, bn c th mun cut out ngi trung gian v lm cc nghch o matrix ring (ph thuc vo data source, iu ny c th tit kim cho bn khi mt chm memory allocations cho cc cc matrix tm bn trong ca cvInvert() hay cvSolve()). Function cvSVBkSb() tnh thay th pha sau cho mt matrix A m c biu din theo dng ca mt phn r ca cc matrix U, W, v V (chng hn mt SVD). Kt qu matrix X c cho bi cng thc: Matrix B laf optional, v nu c t thnh NULL n s c b qua. Matrix W* l * 1 mt matrix m cc diagonal elements c nh ngha bi i = i cho i . Gi tr ny l singularity threshold, mt s rt nh m in hnh t l vi tng ca cc diagonal elements ca W (chng hn

X = V W* UT B

)
i i

cvTrace
Trace ca mt matrix (Trace) l tng tt c cc diagonal element. Trace trong OpenCV c thc hin trn inht ca cvGetDiag() function, do n khng i hi array chuyn vo l vung. Cc Multichannel arrays c h tr, nhng array mat nn l floating-point type.
CvScalar cvTrace( const CvArr* mat );

cvTranspose v cvT

cvTranspose() chp mi element ca src v v tr trong dst nhn bit bi row v column

void cvTranspose( const CvArr* src, CvArr* dst );

index. Function ny h tr multichannel array; tuy nhin, nu bn ang dng multiple channels biu din cc complex number, nh rng cvTranspose() khng thc hin complex conjugation (mt cch nhanh hon thnh nhim v ny bi cc phng tin ca cvXorS() function, m c th c dng trc tip lt du cc bit trong phn o ca array). Macro cvT() n gin tin tay cho cvTranspose().

cvXor v cvXorS

void cvXor( const CvArr* src1, const CvArr* src2,

Hai functions ny tnh bitwise XOR operation trn array src1. Trong trng hp ca cvXor(), mi element ca dst c tnh nh bitwise XOR ca hai elements tng ng ca src1 v src2. Trong trng hp ca cvXorS(), bitwise XOR c tnh vi constant scalar value. Lp li, nu mask l non-NULL th ch cc elements ca dst tng ng vi cc nonzero entry trong mask c tnh. Tt c data types c h tr, nhng src1 v src2 phi c cng data type cho cvXor(). Cho cc floating-point element, biu din bitwise ca floating-point number c dng.

); void cvXorS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );

CvArr* dst, const CvArr* mask=NULL

cvZero

Function ny t tt c values trong tt c channels ca array thnh 0.

void cvZero( CvArr* arr );

Drawing Things
Lines

iu m thng xuyn xy ra l cn v vi th ca picture hay v g ln nh ca mt image c c t u . Toward this end, OpenCV cung cp mt m cc functions m s cho php ta lm cc lines, squares, circles, v khc. n gin nht trong nhng routines ny l v draws line bi Bresenham algorithm [Bresenham65]:
void cvLine( CvArr* array, CvPoint pt1, CvPoint pt2, CvScalar color, int thickness = 1, int connectivity = 8 );

Argument u tin cho cvLine() l CvArr* bnh thng, m trong ng cnh ny in hnh c ngha mt IplImage* image pointer. Hai arguments tip thep l CvPoints. Nh mt gi nh nhanh, CvPoint l mt structure n gin cha ch cc integer members x v y. Ta c th to mt CvPoint trc tip bng routine cvPoint(int x, int y), m gi thun tin hai integers vo mt CvPoint structure cho ta. Argument tip, color, l kiu CvScalar. CvScalars cng l cc structure, m (bn c th nh li) c nh ngha nh sau:
typdef struct { double val[4]; } CvScalar;

Nh bn c th thy, structure ny ch l tp bn s doubles. Trong trng hp ny, ba ci u tin biu din red, green, v blue channels; ci th t khng dng (n c th c dng cho mt alpha channel khi thch hp). Mt in hnh lm vic dng ca handy macro CV_RGB(r, g, b). Macro ny ly ba s v gi chng vo mt CvScalar. Hai arguments tip theo l optional. dy l dy ca line (theo pixels), v s kt t anti-aliasing mode. Mc nh l 8 connected, m s cho mt nice, smooth, antialiased line. Bn c th cng t ci ny thnh 4 connected line; cc diagonal s l th v chc, nhng chng s c v nhanh hn nhiu. D nh cvLine() is cvRectangle(). C l khng cn thit ni vi bn rng cvRectangle() v mt rectangle. N c cng cc argument nh cvLine() ngoi tr rng khng c connectivity argument. y l v cc rectangle kt qu lun lun c hng bng cc cnh song song vi cc trc x- v y-axes. Bng cvRectangle(), ta n gin cho hai im cho cc cnh i din v OpenCV s v rectangle.

void cvRectangle( CvArr* array, CvPoint pt1, CvPoint pt2, CvScalar color, int thickness = 1 );

Circles v Ellipses
void cvCircle ( CvArr* array, CvPoint center, int radius, CvScalar color, int thickness = 1, int connectivity = 8 );

D tng t l method v cc circle, m c cng cc argument.

Cho cc circle, cc rectangle, v tt c cc ng kn khc, thickness argument c th cng c t thnh CV_FILL, m l mt alias cho 1; kt qu l hnh c v s c t cng mu nh cc cnh. Ch phc tp hn mt t vi cvCircle() l routine v cc generalized ellipses:
void cvEllipse( CvArr* img, CvPoint center, CvSize axes, double angle, double start_angle, double end_angle, CvScalar color, int thickness = 1, int line_type = 8 );

Trong trng hp ny, thnh phn chnh mi l axes argument, m l type CvSize. Function CvSize rt ging CvPoint v CvScalar; n l mt structure n gin, trong trng hp ny cha ch cc member width v height. Nh CvPoint v CvScalar, c mt helper function thun tin cvSize(int height, int width) m s return mt CvSize structure khi ta cn mt ci. Trong trng hp ny, cc height v width arguments biu din length ca cc trc major v minor ca ellipse. Angle l gc (theo ) ca major axis, m c o theo counterclockwise t trc honh (chng hn t x-axis). Tng t start_angle v end_angle nhn din (cng theo ) gc cho cung bt u v cho n hon thnh. Do , cho mt ellipse hon chnh bn phi t nhng values ny thnh 0 v 360, tng ng. Mt cch lhacs ch nh v mt ellipse l to dng mt bounding box:
void cvEllipseBox( CvArr* img, CvBox2D box, CvScalar color, int thickness = 1, int line_type = 8, int shift= 0 );

y ln na ta thy mt ci khc ca cc helper structures ca OpenCV, CvBox2D:


typdef struct { CvPoint2D32f center; CvSize2D32f size; float angle; } CvBox2D;

CvPoint2D32f l tng t floating-point ca CvPoint, v CvSize2D32f l tng t floatingpoint ca CvSize. Nhng ci ny, cng vi gc nghing, ch nh hiu qu

bounding box cho ellipse.

Polygons

Cui cng, ta c mt tp cc functions v cc polygon:

Tt c ba ci ny l cc bin i t trn cng tng, vi khc bit chnh l cch cc im c ch nh. Trong cvFillPoly(), cc im c cung cp nh mt array ca cc CvPoint structure. iu ny cho php cvFillPoly() v nhiu polygons trong mt li gi n. Tng t npts l mt array ca point counts, mt cho mi polygon c v. Nu bin is_closed c t thnh true, th mt segment thm s c v t im cui n im u cho mi polygon. cvFillPoly() l rt mnh v s handle cc polygon t ct, polygons vi cc l, v cc phc tp khc nh th. Khng may, iu ny c ngha routine tng i chm. cvFillConvexPoly() lm vic ging cvFillPoly() ngoi tr rng n v mt polygon mt lc v c th draw ch cc convex polygon.* Thun li m l cvFillConvexPoly() chy nhanh hn. Function th ba, cvPolyLine(), ly cng arguments nh cvFillPoly(); tuy nhin, do ch cc cnh polygon c v, t giao biu din khng s phc tp c th. Do function ny nhanh hn nf so vi cvFillPoly().

void cvFillPoly( CvArr* img, CvPoint** pts, int* npts, int contours, CvScalar color, int line_type = 8 ); void cvFillConvexPoly( CvArr* img, CvPoint* pts, int npts, CvScalar color, int line_type = 8 ); void cvPolyLine( CvArr* img, CvPoint** pts, int* npts, int contours, int is_closed, CvScalar color, int thickness = 1, int line_type = 8 );

Fonts v Text

Mt dng cui ca v l i c th cn l v text. D nhin, text to tp ring cc phc tp, nhngnh lun lun vi kiu ny ca vicOpenCV c lin quan nhiu hn bng cung cp mt gii php n gin thp v dirty m s lm cho cc trng hp n gin cases hn l mt gii php mnh, phc tp (m s l d c cho bi cc kh nng ca cc th vin khc). OpenCV c mt routine chnh, gi l cvPutText() m ch nm vaiif text ln mt image. Text nhn din bi text c in bng lower-leftcorner ca n ca text box gn v theo mu ch nh bi color.
void cvPutText( CvArr* img, const char* text, CvPoint origin, const CvFont* font, CvScalar color );

Lun lun c vi th m lm vic ca ta phc tp thm mt t hn ta mun, v trong trng hp ny vic c mt ca pointer n CvFont. Trong mt nutshell, cch ly CvFont* pointer hp l gi function cvInitFont(). Function ny ly mt nhm cc arguments m cuus hnh vi font c th dng trn screen. Nhng ci bn quen vi GUI programming trong cc mi trng khc s tm thy cvInitFont() l nh li cc device tng t nhng vi vi option. to mt

CvFont m ta c th chuyn vo cvPutText(), ta phi u tin khai bo mt CvFont variable; th ta c th chuyn n vo cvInitFont().
void cvInitFont( CvFont* font, int font_face, double hscale, double vscale, double shear = 0, int thickness = 1, int line_type = 8 );

Quan st rng y l mt khc bit nh v cch cc function dng nh tng t, chng hn cvCreateImage(), lm vic trong OpenCV. Li gi n cvInitFont() khi to CvFont structure hin c (m c ngha rng bn to variable v chuyn cho cvInitFont() mt pointer vo variable bn to). y khng ging cvCreateImage(), m to structure cho bn v tr v mt pointer. Argument font_face l mt trong nhng ci c k trong Table 3-15 (v m t trong Figure 3-6), v n c th ty chn c kt hp (bi Boolean OR) bng CV_FONT_ITALIC.
Table 3-15. Available fonts (all are variations of Hershey) Identifier M t CV_FONT_HERSHEY_SIMPLEX Normal size sanserif CV_FONT_HERSHEY_PLAIN Small size sanserif CV_FONT_HERSHEY_DUPLEX Normal size sanserif, more complex than
CV_FONT_HERSHEY_SIMPLEX CV_FONT_HERSHEY_COMPLEX Normal CV_FONT_HERSHEY_DUPLEX CV_FONT_HERSHEY_TRIPLEX Normal CV_FONT_HERSHEY_COMPLEX CV_FONT_HERSHEY_COMPLEX_SMALL CV_FONT_HERSHEY_COMPLEX CV_FONT_HERSHEY_SCRIPT_SIMPLEX CV_FONT_HERSHEY_SCRIPT_COMPLEX CV_FONT_HERSHEY_SCRIPT_SIMPLEX

size serif, more complex than size serif, more complex than Smaller version of Handwriting style More complex variant of

Figure 3-6. Tm fonts ca Table 3-15 v vi hscale = vscale = 1.0, vi gc ca mi line c chia theo chiu ng 30 pixels C hscale v vscale c th c t thnh mt trong 1.0 hay 0.5 only. iu ny lm font

c v height (v width) hay na tng ng vi nh ngha c bn ca font c th. Shear function to nghing cho font; nu t thnh 0.0, font khng nghing. N c th c t ln bng 1.0, m t slope ca cc characters xp x 45 . C thickness v line_type l ging nh c nh ngha cho tt c cc drawing function khc.

Data Persistence

OpenCV cung cp mt c ch serializing v de-serializing cc data types khc nhau vo v ra disk theo mt trong YAML hay XML format. Trong chng v HighGUI, m chuyn v cc user interface function, ta s cp cc function c th m lu v nh li hu ht object ph bin: IplImages (cc functions ny l cvSaveImage() v cvLoadImage()). Thm vo , chng HighGUI s tho lun cc read v write functions c th cho movies: cvGrabFrame(), m c t file hay t camera; v cvCreateVideoWriter() v cvWriteFrame(). Trong phn ny, ta s tp tring vo lu object chung: reading v writing cc matrix, OpenCV structures, v configuration v log files. u tin ta bt u vi cc functions c th v thun li m save v load cc matrix OpenCV. nhng functions ny l cvSave() v cvLoad(). Gi thit bn c mt 5-by-5 identity matrix (0 mi ni ngoi tr ci u trn diagonal). Example 3-15 cho thy cch hon thnh iu ny.
Example 3-15. Saving v loading a CvMat
CvMat A = cvMat( 5, 5, CV_32F, the_matrix_data ); cvSave( my_matrix.xml, &A ); ... // to load it then in some other program dng CvMat* A1 = (CvMat*) cvLoad( my_matrix.xml );

CxCore reference manual cha ton b phn v data persistence. iu bn thc s cn bit l data persistence chung trong OpenCV gm to mt CvFileStorage structure, nh trong Example 3-16, m lu cc memory objects trong mt tree structure. Bn c th to v iu structure ny bi reading t disk qua cvOpenFileStorage() vi CV_STORAGE_READ, hay bn c th to v open CvFileStorage qua cvOpenFileStorage() vi CV_STORAGE_WRITE writing v sau in n dng cc data persistence function thch hp. Trn disk, data c lu theo mt XML hay YAML format.
Example 3-16. CvFileStorage structure; data is accessed by CxCore data persistence functions
typedef struct CvFileStorage { ... // hidden fields } CvFileStorage;

Data ni bn trong CvFileStorage tree c th gm mt tp th bc cc scalars, cc CxCore objects (cc matrix, sequences, v graphs) v/hoc user-defined objects. Hy ni bn c mt configuration hay logging file. V d, xem trng hp ca mt movie configuration file m ni cho ta bao nhiu frames ta mun (10), size ca chng l (320 by 240) v mmm 3-by-3 color conversion matrix m s c p dng. Ta mun gi file cfg.xml trn disk. Example 3-17 cho thy cch lm iu ny.
Example 3-17. Writing a configuration file cfg.xml to disk
CvFileStorage* fs = cvOpenFileStorage( cfg.xml, 0, CV_STORAGE_WRITE ); cvWriteInt( fs, frame_count, 10 ); cvStartWriteStruct( fs, frame_size, CV_NODE_SEQ ); cvWriteInt( fs, 0, 320 ); cvWriteInt( fs, 0, 200 ); cvEndWriteStruct(fs); cvWrite( fs, color_cvt_matrix, cmatrix ); cvReleaseFileStorage( &fs );

Luys vo key function trong v d ny. Ta c th cho tn thnh cc integer m ta vit vo structure dng cvWriteInt(). Ta c th to mt structure ty , dng cvStartWriteStruct(), m cng c cho mt optional name (chuyn 0 hay NULL nu khng c tn). Structure ny c hai int m khng c tn v do ta chuyn 0 cho chng trong name field, sau khi ta dng cvEndWriteStruct() kt thc vit structure . Nu c nhiu structure hn, ta Start v End tng ci tng t; cc structures c th c kt li theo su ty . Ta sau dng cvWrite() vit ra color conversion matrix. Tri vi th tc vit matrix hon ton phc tp ny bng n gin hn cvSave() trong Example 3-15. cvSave() function ch l mt shortcut thun li cho cvWrite() khi bn c ch mt matrix vit. Khi ta hon thnh vit data, CvFileStorage handle c gii phng trong cvReleaseFileStorage(). Output ( y, theo dng XML) s trong nh trong Example 3-18.
Example 3-18. XML version of cfg.xml on disk
<?xml version=1.0?> <opencv_storage> <frame_count>10</frame_count> <frame_size>320 200</frame_size> <color_cvt_matrix type_id=opencv-matrix> <rows>3</rows> <cols>3</cols> <dt>f</dt> <data></data></color_cvt_matrix> </opencv_storage>

Ta c th sau c configuration file ny nh c thy trong Example 3-19.


Example 3-19. Reading cfg.xml from disk
CvFileStorage* fs = cvOpenFileStorage( cfg.xml, 0, CV_STORAGE_READ ); int frame_count = cvReadIntByName( fs,

Khi c, ta m XML configuration file bng cvOpenFileStorage() nh trong Example 319. Ta sau c frame_count dng cvReadIntByName(), m cho php mt value mc nh c cho nu khng c s c c. Trong trng hp ny mc nh l 5. Ta sau ly structure m ta t tn frame_size dng cvGetFileNodeByName() . T y, ta c hai integer khng c tn dng cvReadInt(). Tip theo ta c color conversion matrix c tn dng cvReadByName().* Ln na, tri vi iu ny dng ngn short cvLoad() trong Example 3-15. Ta c th dng cvLoad() nu ta ch c mt matrix c, nhng ta phi dng cvRead() nu matrix c nhng vo trong mt structure ln hn. Cui cng, ta release CvFileStorage structure. List cc data persistence function thch hp kt hp vi CvFileStorage structure c thy trong Table 3-16. Xem CxCore manual cho chi tit hn.
Table 3-16. Data persistence functions

); CvSeq* s = cvGetFileNodeByName(fs,0,frame_size)->data.seq; int frame_width= cvReadInt( (CvFileNode*)cvGetSeqElem(s,0) ); int frame_height = cvReadInt( (CvFileNode*)cvGetSeqElem(s,1) ); CvMat* color_cvt_matrix = (CvMat*) cvReadByName( fs, 0, color_cvt_matrix ); cvReleaseFileStorage( &fs );

0, frame_count, 5 /* default value */

Function M t

Open v Release cvOpenFileStorage Opens file storage for reading hay writing cvReleaseFileStorage Releases data storage Writing cvStartWriteStruct Starts writing a new structure cvEndWriteStruct Ends writing a structure cvWriteInt Writes integer cvWriteReal Writes float cvWriteString Writes text string cvWriteComment Writes an XML hay YAML comment string cvWrite Writes mt object chng hn a CvMat cvWriteRawData Writes multiple numbers cvWriteFileNode Writes file node to mt ci khc file storage Table 3-16. Data persistence functions (continued)

Function M t
Reading
cvGetRootFileNode Gets the top-level nodes of the file storage cvGetFileNodeByName Finds node in the map hay file storage cvGetHashedKey tr v a unique pointer for given name cvGetFileNode Finds node in the map hay file storage cvGetFileNodeName tr v name of file node cvReadInt Reads unnamed int cvReadIntByName Reads named int cvReadReal Reads unnamed float cvReadRealByName Reads named float cvReadString Retrieves text string from file node cvReadStringByName Finds named file node v tr v its value cvRead Decodes object v tr v pointer to it cvReadByName Finds object v decodes it cvReadRawData Reads multiple numbers cvStartReadRawData Initializes file node sequence reader cvReadRawDataSlice Reads data from sequence reader above

Function M t
Reading
cvGetRootFileNode Gets the top-level nodes of the file storage cvGetFileNodeByName Finds node in the map hay file storage cvGetHashedKey tr v a unique pointer for given name cvGetFileNode Finds node in the map hay file storage cvGetFileNodeName tr v name of file node cvReadInt Reads unnamed int cvReadIntByName Reads named int cvReadReal Reads unnamed float cvReadRealByName Reads named float cvReadString Retrieves text string from file node cvReadStringByName Finds named file node v tr v its value cvRead Decodes object v tr v pointer to it cvReadByName Finds object v decodes it cvReadRawData Reads multiple numbers cvStartReadRawData Initializes file node sequence reader cvReadRawDataSlice Reads data from sequence reader above

Integrated Performance Primitives

Intel c mt sn phm gi l Integrated Performance Primitives (IPP) library (IPP). Th vin ny thc s l mt toolbox ca cc li hiu sut cao handling multimedia v cc tc v tiu th processor khc theo cch m lm m rng vic dng kin trc chi tit ca cc processor ca h (v, mt tha thun t hi, cc processors ca cc nh sn xut khc m c cng kin trc). Nh c tho lun trong chng 1, OpenCV thch quan h gn vi IPP, c hai mc phn mm v mt mc t chc bn trong ca cng ty ny. Nh mt kt qu, OpenCV c thit k t ng nhn ra s c mt ca IPP library v t ng hon i cc thc hin hiu sut thp ca nhiu chc nng li thnh cc higherperformance counterparts trong IPP. IPP library cho php OpenCV ly cc thun li ca ti u hiu sut m n t cc lnh SIMD trong mt single processor cng nh t cc kin trc multicore hin i. Vi nhng c bn ny trong tay, ta c th thc hin lng ln cc nhim v c bn. Tin ln qua text ny, ta s quan st nhiu kh nng phc tp hn ca OpenCV, hu ht tt c m c to trn nhng routines ny. N s khng ngc nhin rng image processingm thng i hi lm cng th trn lng ln data, m phn ln l hon ton parallelm hin thc mt thun li ln t bt k code m cho php n c thun li ca cac n v thc thi song song ca bt k dng no (MMX, SSE, SSE2, etc.).

Verifying Installation

Cch kim tra v m bo rng IPP c ci v lm vic thch hp bng function cvGetModuleInfo(), c thy trong Example 3-20. Function ny s nhn c version ca OpenCV bn hin ang chy v version v nhn bt k add-in modules.
Example 3-20. dng cvGetModuleInfo() to check for IPP
char* libraries; char* modules; cvGetModuleInfo( 0, &libraries, &modules ); printf(Libraries: %s/nModules: %s/n, libraries, modules );

Code trong Example 3-20 s to cc text string m m t cc installed libraries v modules. Output c th trng nh th ny:
Libraries cxcore: 1.0.0 Modules: ippcv20.dll, ippi20.dll, ipps20.dll, ippvm20.dll

Cc modules k trong output ny l cc IPP modules dng bi OpenCV. Cc modules ny t chng thc s x l cho ngay c cc lower-level CPU-specific libraries. Chi tit cch n tt c lm vic nm ngoi phm vi sch ny, nhng nu bn thy cc IPP libraries trong Modules string th bn c th be pretty confident that mi th is working nh mong i. D nhin, bn c th dng thng tin ny to kim tra that IPP is running correctly on your own system. Bn c th cng dng it to check for IPP on a

machine on which your finished software is installed, perhaps then making some dynamic adjustments ph thuc vo c hay khng IPP is available.

Tm tt

In chng ny ta introduced some basic data structures that ta s often trm chn. V c th, ta met the OpenCV matrix structure v the all-important OpenCV image structure, IplImage. ta considered both in some detail v found that the matrix v image structures are rt similar: the functions used for primitive manipulations in one work equally well in the other.

Exercises

In the following exercises, bn c th need to refer to the CxCore manual that ships with OpenCV hay to the OpenCV Wiki on the Web for details of the functions outlined in chng ny. Find v 1. d open .../opencv/cxcore/include/cxtypes.h. Read through v tm thy the many conversion helper functions. a. , and then take its ceiling v floor. b. Generate some random numbers. c. to a floating point CvPoint2D32f v convert it to an integer CvPoint. d. Convert a CvPointer n a CvPoint2D32f. 2. This exercise s accustom bn to the idea of nhiu functions taking matrix types. Create a two-dimensional matrix with three channels of type byte with data size 100-by-100. Set tt c the values to 0. a. Draw a circle in the matrix dng void cvCircle( CvArr* img, CvPoint center,
intradius, CvScalar color, int thickness=1, int line_type=8, int shift=0 ).

b. Display this image dng methods described in chng 2. 3. to a two-dimensional matrix with three channels of type byte with data size 100-by-100, v set tt c the values to 0. dng the pointer element truy cp function cvPtr2D to tr n the middle (green) channel. Draw a green rectangle between (20, 5) v (40, 20). 4. to a three-channel RGB image of size 100-by-100. Clear it. dng pointer arithmetic to draw a green square gia (20, 5) v (40, 20). 5. Practice dng region of interest (ROI). to a 210-by-210 single-channel byte image and zero it. With in the image, build a pyramid of increasing values dng ROI and cvSet(). That is: the outer border should be 0, the next inner border should be 20, the next inner border should be 40, v so on until the final innermost square is set to value 200; tt c borders should be 10 pixels wide. Display the image. 6. dng multiple image headers for one image . Load mt image that is ti thiu 100by-100. Create hai additional image headers v set their origin, depth, number of channels, and widthstep to be the same as the loaded image. In the new image headers, set the widthat 20 v the height at 30. Cui cng, set their imageData pointers to point to the pixel at (5, 10) v (50, 60), respectively. Pass nhng ci ny new image subheaders to cvNot(). Display the loaded image, m should have hai inverted rectangles with in the larger image. 7. to a mask dng cvCmp(). Load a real image. dng cvSplit() to split the image into red, green, v blue images. a. tm thy v display the green image. b. Clone this green plane image twice (call nhng ci ny clone1 v clone2). c. tm thy the green planes minimum v maximum value. d. Set clone1s values to thresh = (unsigned char)((maximum - minimum)/2.0).

e. Set clone2 to 0 v dng cvCmp(green_image, clone1, clone2, CV_CMP_GE). Now clone2 s have a mask of where the value exceeds thresh in the green image. f. e cvSubS(green_image,thresh/2, green_image, clone2) v display the results. 8. to a structure of an integer, a CvPoint v a CvRect; call it my_struct. a. Write hai functions: void write_my_struct( CvFileStorage * fs, const char *
name, my_struct *ms) v void read_my_struct( CvFileStorage* fs, CvFileNode* ms_node, my_struct* ms ). dng them to write v read my_struct. b. Write v read an array of 10 my_struct structures.

You might also like