Professional Documents
Culture Documents
Ce document prsente les bases indispensables l'utilisation d'OpenCV travers son interface C++, la documentation technique d'OpenCV peut tre consulte en ligne. La cheat sheet c++ permet en outre de trouver facilement une fonction ou un type de donnes.
Sommaire
Introduction OpenCV ............................................................................................................................ 1 Introduction......................................................................................................................................... 2 Prsentation d'OpenCV ................................................................................................................... 2 Convention de nommage ................................................................................................................ 2 Compilation ..................................................................................................................................... 3 Premire exemple C++ : .................................................................................................................. 3 Structures de donnes de base ........................................................................................................... 4 Les points Point_........................................................................................................................... 4 Dimension Size_............................................................................................................................ 4 Rectangle Rect_ ............................................................................................................................ 4 Vecteur - Vec ................................................................................................................................... 5 Image Mat .................................................................................................................................... 6 Utilisation de la classe Mat.................................................................................................................. 6 Cration d'une nouvelle image ........................................................................................................... 6 Accs aux pixels d'une image .............................................................................................................. 7 Image en niveau de gris................................................................................................................... 7 Image multibande couleur ........................................................................................................... 8 Affichage et enregistrement des images............................................................................................. 9 Affichage d'une image ..................................................................................................................... 9 Enregistrement d'une image ......................................................................................................... 10
Introduction
Prsentation d'OpenCV OpenCV : est une librairie open source de traitement et analyse d'images et vidos avec des interfaces pour les principaux langages de programmation C, C++, Java, C#, Python ... est optimise pour les applications temps relles fournit une API bas et haut niveau fournit une interface pour le langage de programmation parallle IPP est utilis aussi bien dans les laboratoires de recherche que dans l'industrie
Fonctions : manipulation d'images (chargement, sauvegarde, copie, conversion...) manipulation et acquisition de videos manipulations de matrices et algbre linaire structure de donnes utilitaires varies (listes, files, ensembles, graphes...) traitement d'images (filtrage, dtections de discontinuits, morphologie mathmatique...) analyse d'images (composantes connexes, ajustement de primitives, transforme de distance...) vision (calibration de camra, stereovision, recherche d'association...) reconnaissance de forme (modles de markov, ACP...) interface graphique (affichage d'images, de vidos, gestion des vnements...)
Modules : cv - Main OpenCV functions. cvaux - Auxiliary (experimental) OpenCV functions. cxcore - Data structures and linear algebra support. highgui - GUI functions.
Exemple : CV_8UC1 signifie une matrice dont les lments sont des entiers non signs cods sur 8-bits CV_32FC2 signifie une matrice possdant deux canaux (2 valeurs par position) dont les lments sont des nombres flottants cods sur 32-bit.
Header inclure :
#include <cv.h> #include <cvaux.h> #include <highgui.h>
Compilation
g++ source.cpp -o mon_programme `pkg-config --cflags opencv` -libs opencv` `pkg-config -
//////////////////////////////////////////////////////////////////////// // inverse.cpp // // This is a simple, introductory OpenCV program. The program reads an // image from a file, inverts it, and displays the result. //////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include <stdio.h> #include <math.h> #include <cv.h> #include <highgui.h> using namespace std; using namespace cv; int main(int argc, char *argv[]) { // load an image Mat img=imread("camera.png",0); if(img.empty()){ printf("Could not load image file\n"); exit(0); } // get the image data int height = img.rows; int width = img.cols; printf("Processing a %dx%d image\n",height,width); // invert the image for(int i=0;i<height;i++) for(int j=0;j<width;j++) img.at<uchar>(i,j)=255-img.at<uchar>(i,j); // create a window namedWindow("mainWin", CV_WINDOW_AUTOSIZE); // show the image imshow("mainWin", img ); // wait for a key waitKey(0); return 0; }
Pour les types courants : points coordonnes entires, flottantes, simple ou double prcision, on dispose des alias suivants:
typedef typedef typedef typedef Point_<int> Point2i; Point2i Point; Point_<float> Point2f; Point_<double> Point2d;
Exemple d'utilisation :
Point2f a(0.3f, 0.f), b(0.f, 0.4f); Point pt = (a + b)*10.f; cout << pt.x << ", " << pt.y << endl;
Dimension Size_ Reprsente la taille d'un objet rectangulaire a 2 dimensions. Comme pour les points il s'agit d'une structure gnrique.
template<typename _Tp> class Size_ { public: Size_(); Size_(_Tp _width, _Tp _height); Size_(const Size_& sz); _Tp area() const; ... _Tp width, height; };
Rectangle Rect_ Reprsente un rectangle. Un rectangle est la donne d'un point (le coin suprieur gauche) et d'une taille. C'est galement une structure gnrique.
template<typename _Tp> class Rect_ { public:
Rect_(); Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height); Rect_(const Rect_& r); // (x, y) <- org, (width, height) <- sz Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz); // (x, y) <- min(pt1, pt2), (width, height) <- max(pt1, pt2) - (x, y) Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2); // returns Point_<_Tp>(x, y) Point_<_Tp> tl() const; // returns Point_<_Tp>(x+width, y+height) Point_<_Tp> br() const; // returns Size_<_Tp> // returns _Tp area() Size_<_Tp>(width, height) size() const; width*height const;
// x <= pt.x && pt.x < x + width && // y <= pt.y && pt.y < y + height ? true : false bool contains(const Point_<_Tp>& pt) const; _Tp x, y, width, height; };
Vecteur - Vec Reprsente un vecteur gnrique de faible dimension (<10). A ne pas confondre avec le type Vecteur de la STL qui correspond un tableau dynamique.
template<typename _Tp, int cn> class Vec { public: // default constructor: all elements are set to 0 Vec(); // constructors taking up to 10 first elements as parameters Vec(_Tp v0); Vec(_Tp v0, _Tp v1); ... Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9); Vec(const Vec<_Tp, cn>& v); // constructs vector with all the components set to alpha. static Vec all(_Tp alpha); ... //data _Tp val[cn]; };
Image Mat C'est le type fondamental pour reprsenter toutes les sortes d'images. On peut noter que la dfinition n'utilise pas la gnricit. Les matrices disposent d'une gestion automatique de la mmoire, il n'y a donc pas de free ou delete ajouter manuellement.
class CV_EXPORTS Mat { public: // ... a lot of methods ... ... //! the array dimensionality, >= 2 int dims; //! the number of rows and columns or (-1, -1) when the array has more than 2 dimensions int rows, cols; //! pointer to the data uchar* data; };
Paramtres :
filename Name of file to be loaded. flags Specifies color type of the loaded image: o >0 the loaded image is forced to be a 3-channel color image o =0 the loaded image is forced to be grayscale o <0 the loaded image will be loaded as-is.
Allocation par constructeur : La classe Mat propose un nombre important de constructeur, viola ceux qui vous seront le plus utile :
Mat::Mat(int rows, int cols, int type) Mat::Mat(Size size, int type)
Paramtres :
Exemple :
// allocate a matrix of 1024 rows by 768 columns with 32 bits floating precison and 3 channels Mat im1(1024,768,CV_32FC3); Size s(768,1024); // allocate a matrix of 1024 rows by 768 columns with unsigned 8 bits integer precison and 1 channel Mat im2(s,CV_8UC1);
rows Number of rows in a 2D array. cols Number of columns in a 2D array. size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the number of columns go in the reverse order. type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices
Paramtres : Exemple :
Mat img(100, 100, CV_64FC1); for(int i = 0; i < img.rows; i++) for(int j = 0; j < img.cols; j++) img.at<double>(i,j) = 1./(i+j+1); Mat img2(100,100,CV_8UC1); for(int i = 0; i < img2.rows; i++) for(int j = 0; j < img2.cols; j++) img.at<uchar>(i,j) = saturate_cast<uchar>(img.at<double>(i,j)*1000.0);
i The row index (start at 0) j The column index (start at 0) pt The element position specified as Point(j,i)
Remarque : saturate_cast<datatype> est une function qui convertit un argument numrique dans le type numrique demand mais ralise une saturation au lieu d'une troncature binaire lorsqu'un dbordement se produit.
ushort x = 257; // en binaire : 100000001b uchar y = (uchar)x; // transtypage simple, on garde les 8 bits de droites : 00000001b = 1 uchar z = saturate_cast<uchar>(x); // transtypage avec saturation, on prend la plus grande valeur reprsentable par uchar = 255
Premire mthode avec at : Approche similaire la prcdente mais cette fois at va nous donner un vecteur de dimension le nombre de canaux dans l'image. Exemple : on peut modifier le premier exemple qui inverse une image pour prendre en charge les images couleurs en remplaant les boucles par:
// invert the image for(int i=0;i<height;i++) for(int j=0;j<width;j++) img.at<Vec3b>(i,j)=Vec3b(255,255,255)-img.at<Vec3b>(i,j);
On traite donc directement des triplets RGB reprsents sous forme de Vec3b. On aurait galement pu crire, sans utiliser les oprations vectorielles pr-dfinies:
// invert the image for(int i=0;i<height;i++) for(int j=0;j<width;j++) { Vec3b v = img.at<Vec3b>(i,j); v[0] = 255 - v[0]; v[1] = 255 - v[1]; v[2] = 255 - v[2]; img.at<Vec3b>(i,j)=v; }
Mthode par dcoupage en plan : Cette approche consiste simplement dcouper une image n canaux en n image 1 canal, traiter chaque canal, puis les rassembler. La sparation des canaux se fait grce fonction split, les canaux sont mis dans un vecteur (stl) de Mat. La fonction merge assemble plusieurs images 1 canal contenues dans un vecteur de Mat en une unique image. Exemple :
// split the image into separate color planes vector<Mat> planes; split(img, planes); // invert the 3 planes for(int c=0;c<planes.size();c++) for(int i=0;i<height;i++) for(int j=0;j<width;j++) planes[c].at<uchar>(i,j)=255-planes[c].at<uchar>(i,j); // now merge the results back merge(planes, img);
L'affichage d'une image se realize en deux temps (+ un troisime optionnel): 1. Cration d'une fentre nomme avec namedWindow void namedWindow(const string& winname, int flags) Paramtres :
name Name of the window in the window caption that may be used as a window identifier. flag (QT-backend only) combined with a OR operation o CV_WINDOW_NORMAL or CV_WINDOW_AUTOSIZE: CV_WINDOW_NORMAL let the user resize the window, whereas CV_WINDOW_AUTOSIZE adjusts automatically the windows size and the user can not change the window size manually. o CV_WINDOW_FREERATIO or CV_WINDOW_KEEPRATIO: CV_WINDOW_FREERATIO adjust the image without respect the its ration, whereas CV_WINDOW_KEEPRATIO keep the images ratio. o CV_GUI_NORMAL or CV_GUI_EXPANDED: CV_GUI_NORMAL is the old way to draw the window without statusbar and toolbar, whereas CV_GUI_EXPANDED is the new enhance GUI.
2.
3.
Un appel waitKey pour viter que le programme ne s'arrte immdiatement fin de la fonction main.
Exemple :
// create a window namedWindow("mainWin", CV_WINDOW_AUTOSIZE); // show the image imshow("mainWin", img ); // wait for a key waitKey(0);
Enregistrement d'une image L'enregistrement se fait avec imwrite bool imwrite(const string& filename, const Mat& img, const vector<int>& params=vector<int>()) Paramtres :
filename Name of the file, the extension determine the image format. img The image to be saved. params (optional) The format-specific save parameters, encoded as pairs paramId_1, paramValue_1, paramId_2, paramValue_2, ... . The following parameters are currently supported: o In the case of JPEG it can be a quality ( CV_IMWRITE_JPEG_QUALITY ), from 0 to 100 (the higher is the better), 95 by default. o In the case of PNG it can be the compression level ( CV_IMWRITE_PNG_COMPRESSION ), from 0 to 9 (the higher value means smaller size and longer compression time), 3 by default. o In the case of PPM, PGM or PBM it can a binary format flag ( CV_IMWRITE_PXM_BINARY ), 0 or 1, 1 by default.