Mat:
在2001年刚刚出现的时候,OpenCV基于 C 语言接口而建。为了在内存(memory)中存放图像,当时采用名为 IplImage 的C语言结构体,时至今日这仍出现在大多数的旧版教程和教学材料。但这种方法必须接受C语言所有的不足,这其中最大的不足要数手动内存管理,其依据是用户要为开辟和销毁内存负责。虽然对于小型的程序来说手动管理内存不是问题,但一旦代码开始变得越来越庞大,你需要越来越多地纠缠于这个问题,而不是着力解决你的开发目标。
幸运的是,C++出现了,并且带来类的概念,这给用户带来另外一个选择:自动的内存管理(不严谨地说)。这是一个好消息,如果C++完全兼容C的话,这个变化不会带来兼容性问题。为此,OpenCV在2.0版本中引入了一个新的C++接口,利用自动内存管理给出了解决问题的新方法。使用这个方法,你不需要纠结在管理内存上,而且你的代码会变得简洁(少写多得)。但C++接口唯一的不足是当前许多嵌入式开发系统只支持C语言。所以,当目标不是这种开发平台时,没有必要使用 旧 方法(除非你是自找麻烦的受虐狂码农)。
关于 Mat ,首先要知道的是你不必再手动地(1)为其开辟空间(2)在不需要时立即将空间释放。但手动地做还是可以的:大多数OpenCV函数仍会手动地为输出数据开辟空间。当传递一个已经存在的 Mat 对象时,开辟好的矩阵空间会被重用。也就是说,我们每次都使用大小正好的内存来完成任务。
基本上讲 Mat 是一个类,由两个数据部分组成:矩阵头(包含矩阵尺寸,存储方法,存储地址等信息)和一个指向存储所有像素值的矩阵(根据所选存储方法的不同矩阵可以是不同的维数)的指针。矩阵头的尺寸是常数值,但矩阵本身的尺寸会依图像的不同而不同,通常比矩阵头的尺寸大数个数量级。因此,当在程序中传递图像并创建拷贝时,大的开销是由矩阵造成的,而不是信息头。OpenCV是一个图像处理库,囊括了大量的图像处理函数,为了解决问题通常要使用库中的多个函数,因此在函数中传递图像是家常便饭。同时不要忘了我们正在讨论的是计算量很大的图像处理算法,因此,除非万不得已,我们不应该拷贝 大 的图像,因为这会降低程序速度。
为了搞定这个问题,OpenCV使用引用计数机制。其思路是让每个 Mat 对象有自己的信息头,但共享同一个矩阵。这通过让矩阵指针指向同一地址而实现。而拷贝构造函数则 只拷贝信息头和矩阵指针 ,而不拷贝矩阵
C++版本 好处: |
1、在于可以尽量避免使用指针这种危险的东西; 2、不用费心去release资源了,因为在其destructor里面,系统会自动帮你搞定。 3、在某些情况下会比C版本运行速度快。 在文件中包含 using namespace cv; C 可以移植到硬件上,如dsp C++的功能更丰富,函数稍微多一些 对于功能相同的函数,C的和C++几乎是一样的 |
C++接口利用自动内存管理给出了解决问题的新方法。使用这个方法,你不需要纠结在管理内存上,而且你的代码会变得简洁(少写多得)。 但C++接口唯一的不足是当前许多嵌入式开发系统只支持C语言,c的可移植性要強于c++。所以,当目标不是这种开发平台时,没有必要使用旧方法(除非你是自找麻烦的受虐狂码农)。
1. imread(cvLoadImage):loads an image from a file;
C++: Mat imread(const string& filename, int flags=1 )
Parameters: |
filename – Name of file to be loaded. flags –Flags specifying the color type of a loaded image: >0 Return a 3-channel color image =0 Return a grayscale image <0 Return the loaded image as is. Note that in the current implementation the alpha channel, if any, is stripped from the output image. For example, a 4-channel RGBA image is loaded as RGB if flags>=0. |
2. imshow(cvShowImage):displays an image in the specifiedwidow;
C++: void imshow(const string& winname, InputArray image)
Parameters: |
winname – Name of the window.
the image is shown with its original size. Otherwise, the image is scaled to fit the window. The function may scale the image, depending on its depth: If the image is 8-bit unsigned, it is displayed as is. If the image is 16-bit unsigned or 32-bit integer, the pixels are divided by 256. That is, the value range [0,255*256] is mapped to [0,255]. If the image is 32-bit floating-point, the pixel values are multiplied by 255. That is, the value range [0,1] is mapped to [0,255]. |
3. waitKey(cvWaitKey):waits for a pressed key;
C++: int waitKey(int delay=0)
C: int cvWaitKey(int delay=0 )
4. cvtColor(cvCvtColor):converts an image from one colorspace to another;
5. reduce(cvReduce):reduces a matrix to a vector;
6. minMaxLoc(cvMinMaxLoc):finds the global minimum andmaximum in a whole array or sub-array;
7. namedWindow(cvNamedWindow):creates a window;
8. destroyWindow(cvDestroyWindow):destroys a window;
9. destroyAllWindows(cvDestroyAllWindows):destroys all of the HighGUIwindows;
10. imwrite(cvSaveImage):saves an image to a specified file;
11. resize(cvResize):resizes an image;
12. pyrDown(cvPyrDown):blurs an image and downsamples it;
13. pyrUp(cvPyrUp):upsamples an image and then blursit;
14. threshold(cvThreshold):applies a fixed-level threshold toeach array element;
15. adaptiveThreshold(cvAdaptiveThreshold):applies an adaptive threshold toan array;
16. VideoCapthure::open(cvCaptureFromFile):open video file or a capturingdevice for video capturing;
17. VideoCapture::isOpened:returns true if video capturinghas been initialized already;
18. VideoCapture::release(cvReleaseCapture):closes video file or capturingdevice;
19. VideoCapture::grab(cvGrabFrame):grabs the next frame from videofile or capturing device;
20. VideoCaputre::retrieve(cvRetrieveFrame):decodes and returns the grabbedvideo frame;
21. VideoCapture::read(cvQueryFrame):grabs,decodes and returns the nextvideo frame;
22. VideoCapture::get(cvGetCaptureProperty):returns the specified VideoCaptureproperty;
23. VideoCapture::set(cvSetCaptureProperty):sets a property in theVideoCapture;
24. VideoWriter::open:initializes or reinitializes videowriter;
25. VideoWriter::isOpened:returns true if video writer hasbeen successfully initialized;
26. VideoWriter::write:writes the next video frame;
27. Mat::row:creates a matrix header for thespecified matrix row;
28. Mat::col:creates a matrix header for thespecified matrix column;
29. Mat::rowRange:creates a matrix header for thespecified row span;
30. Mat::colRange:creates a matrix header for thespecified col span;
31. Mat::diag:extracts a diagonal from a matrix,or creates a diagonal matrix;
32. Mat::clone:creates a full copy of the arrayand the underlying data;
33. Mat::copyTo(cvCopy):copies the matrix to another one;
34. Mat::convertTo(cvConvertScale):converts an array to anotherdatatype with optional scaling;
35. Mat::assignTo:provides a functional form ofconvertTo;
36. Mat::setTo:sets all or some of the arrayelements to the specified value;
37. Mat::reshape:changes the shape and/or thenumber of channels of a 2D matrix without copying the data;
38. Mat::t:transposes a matrix;
39. Mat::inv:inverses a matrix;
40. Mat::mul:performs an element-wisemultiplication or division of the two matrices;
41. Mat::cross:computes a cross-product of two3-element vectors;
42. Mat::dot:computes a dot-product of twovectors;
43. Mat::zeros:returns a zero array of thespecified size and type;
44. Mat::ones:returns an array of all 1’s of thespecified size and type;
45. Mat::eye:returns an identity matrix of thespecified size and type;
46. Mat::create:allocates new array data if needed;
47. Mat::addref:increments the reference counter;
48. Mat::release:decrements the reference counterand deallocates the matrix if needed;
49. Mat::resize:changes the number of matrix rows;
50. Mat::reserve:reserves space for the certainnumber of rows;
51. Mat::push_back:adds elements to the bottom of thematrix;
52. Mat::pop_back:removes elements from the bottomof the matrix;
53. Mat::locateROI:locates the matrix header within aparent matrix;
54. Mat::adjustROI:adjusts a submatrix size andposition within the parent matrix;
55. Mat::operator:extracts a rectangular submatrix;
56. Mat::operatorCvMat:creates the CvMat header for thematrix;
57. Mat::operatorIplImage:creates the IplImage header forthe matrix;
58. Mat::total:returns the total number fo arrayelements;
59. Mat::isContinuous:reports whether the matrix iscontinuous or not;
60. Mat::elemSize:returns the matrix element size inbytes;
61. Mat::elemSize1:returns the size of each matrixelement channel in bytes;
62. Mat::type:returns the type of a matrixelement;
63. Mat::depth:returns the depth of a matrixelement;
64. Mat::channels:returns the number of matrix channels;
65. Mat::step1:returns a normalized step;
66. Mat::size:returns a matrix size;
67. Mat::empty:returns true if the array has noelemens;
68. Mat::ptr:returns a pointer to the specifiedmatrix row;
69. Mat::at:returns a reference to thespecified array element;
70. Mat::begin:returns the matrix iterator andsets it to the first matrix element;
71. Mat::end:returns the matrix iterator andsets it to the after-last matrix element;
72. calcHist(cvCalcHist):calculates a histogram of a set ofarrays;
73. compareHist(cvCompareHist):compares two histograms;
74. equalizeHist(cvEqualizeHist):equalizes the histogram of agrayscale image(直方图均衡化);
75. normalize:normalizes the norm or value rangeof an array;
76. CascadeClassifier::CascadeClassifier:loads a classifier from a file;
77. CascadeClassifier::empth:checks whether the classifier hasbeen loaded;
78. CascadeClassifier::load(cvLoadHaarClassifierCascade):loads a classifier from a file;
79. CascadeClassifier::read:reads a classifier from aFileStorage node;
80. CascadeClassifier::delectMultiScale(cvHaarDetectObjects):detects objects of different sizesin the input image(检测图像中的目标);
81. CascadeClassifier::setImage(cvSetImagesForHaarClassifierCascade):sets an image for detection(隐藏的cascade(hidden cascade)指定图像);
82. CascadeClassifier::runAt(cvRunHaarClassifierCascade):runs the detector at the specifiedpoint(在给定位置的图像中运行cascade of boosted classifier);
83. groupRectangles:groups the object candidaterectangles;
84. split(cvSplit):divides a multi-channel array intoseveral single-channel arrays;
85. merge(cvMerge):creates one multichannel array outof several single-channel ones;
86. mixChannels(cvMixChannels):copies specified channels frominput arrays to the specified channels of output arrays;
87. setMouseCallback(cvSetMouseCallback):sets mouse handler for thespecified window;
88. bilateralFilter:applies the bilateral filter to animage(双边滤波);
89. blur(cvSmooth):blurs an image using thenormalized box filter(均值模糊);
90. medianBlur:blurs an image using the medianfilter(中值模糊);
91. boxFilter:blurs an image using the boxfilter;
92. GaussianBlur:blurs an image using a Gaussianfilter(高斯模糊);
93. getGaussianKernel:returns Gaussian filtercoefficients;
94. sepFilter2D:applies a separable linear filterto an image;
95. filter2D(cvFilter2D):convolves an image with the kernel;
96. norm(cvNorm):calculates an absolute array norm,an absolute difference norm, or a relative defference norm;
97. flip(cvFlip):filps a 2D array around vertical,horizontal, or both axes;
98. Algorithm::get:returns the algorithm parameter;
99. Algorithm::set:set the algorithm parameter;
100. Algorithm::write:stores algorithm parameters in afile storage;
101. Algorithm::read:reads algorithm parameters from afile storage;
102. Algorithm::getList:returns the list of registeredalgorithms;
103. Algorithm::create:creates algorithm instance by name;
104. FaceRecognizer::train:trains a FaceRecognizer with givendata and associated labels;
105. FaceRecognizer::update:updates a FaceRecognizer withgiven data and associated labels;
106. FaceRecognizer::predict:predicts a label and associatedconfidence(e.g. distance) for a given input image;
107. FaceRecognizer::save:saves a FaceRecognizer and itsmodel state;
108. FaceRecognizer::load:loads a FaceRecognizer and itsmodel state;
109. createEigenFaceRecognizer:;
110. createFisherFaceRecognizer:;
111. createBPHFaceRecognizer:;
112. getTextSize(cvGetTextSize):calculates the width and height ofa textstring;
113. putText(cvPutText):draws a text string;
114. getStructuringElement(cvCreateStructingElementEx):returns a structuring element ofthe specified size and shape for morphological operations;
115. morphologyEx(cvMorphologyEx):performs advanced morphologicaltransformations;
116. findContours(cvFindContours):finds contours in a binary image;
117. drawContours(cvDrawContours):draw contours outlines or filledcontours;
118. minAreaRect(cvMinAreaRect2):finds a rotated rectangle of theminimum area enclosing the input 2D point set;
119. floodFill(cvFloodFill):fills a connected component withthe given color;
120. getRectSubPix(cvGetRectSubPix):retrieves a pixel rectangle froman image with sub-pixel accuracy;
121. CvSVM::CvSVM:default and training constructors;
122. CvSVM::train:trains an SVM;
123. CvSVM::train_auto:trains an SVM with optimalparameters;
124. CvSVM::predict:predicts the response for inputsample(s);
125. CvSVM::get_default_grid:generates a grid for SVMparameters;
126. CvSVM::get_params:returns the current SVM parameters;
127. CvSVM::get_support_vector:retrieves a number of supportvectors and the particular vector;
128. CvSVM::get_var_count:returns thenumber of used features(variables count);
129. CvANN_MLP(multi-layerperceptrons)::CvANN_MLP:the constructors;
130. CvANN_MLP::create:constructs MLP with the specifiedtopology;
131. CvANN_MLP::train:trains/updates MLP;
132. CvANN_MLP::predict:predicts responses for inputsamples;
133. CvANN_MLP::get_layer_count:returns the number fo layers inthe MLP;
134. CvANN_MLP::get_layer_size:returns numbers of neurons in eachlayer of the MLP;
135. CvANN_MLP::get_weights:returns neurons weights of theparticular layer;
136. CvKNearest::CvKNearest:default and training constructors;
137. CvKNearest::train:trains the model;
138. CvKNearest::find_nearest:finds the neighbors and predictsresponses for input vectors;
139. CvKNearest::get_max_k:returns the number of maximumneighbors that may be passed to the method CvKNearest::find_nearest();
140. CvKNearest::get_var_count:returns the number of usedfeatures(variables count);
141. CvKNearest::get_sample_count:returns the total number of trainsamples;
142. CvKNearest::is_regression:returns type of the problem(truefor regression and false for classification);
143. HoughLines(cvHoughLines):finds lines in a binary imageusing the standard Hough transform;
144. HoughLinesP:finds line segments in a binaryimage using the probabilistic Hough transform;
145. HoughCircles(cvHoughCircles):finds circles in a grayscale imageusing the Hough transform;
146. line(cvLine):draws a line segment connectingtwo points;
147. fitLine(cvFitLine):fits a line to a 2D or 3D pointset;
148. fitEllipse(cvFitEllipse2):fits an ellipse around a set of 2Dpoints;
149. ellipse(cvEllipse、cvEllipseBox):draws a simple or thick ellipticarc or fills an ellipse sector;
150. boundingRect(cvBoundingRect):calculatesthe up-right bounding rectangle of a point set;
151. rectangle(cvRectangle):draws a simple, thick, or filledup-right rectangle;
152. minEnclosingCircle(cvMinEnclosingCircle):finds acircle of the minimum area enclosing a 2D point set;
153. circle(cvCircle):draw a circle;
154. fillPoly:fills the area bounded by one ormore polygons;
155. approxPolyDP(cvApproxPoly):approximates a polygonal curve(s)with the specified precision;
156. pointPolygonTest(cvPointPolygonTest):performs a point-in-contour test(判断点在多边形中的位置);
157. convexHull(cvConvexHull2):finds the convex hull of a pointset;
158. transpose(cvTranspose):transposes a matrix;
159. invert(cvInvert):finds the inverse orpseudo-inverse of a matrix;
160. getStructuringElement(cvCreateStructuringElementEx):returns a structuring element ofthe specified size and shape for morphological operations;
161. absdiff(cvAbsDiff):calculates the per-elementabsolute difference between two arrays or between an array and a scalar;
162. subtract(cvSub):calculates the per-elementdifference between two arrays or array and a scalar;
163. multiply(cvMul):calculates the per-element scaledproduct fo two arrays;
164. divide(cvDiv):performs per-element division oftwo arrays or a scalar by an array;
165. bitwise_or(cvOr):calculates the per-elementbit-wise disjunction of two arrays or an array and a scalar;
166. bitwise_and(cvAnd):calculates the per-elementbit-wise conjunction of two arrays or an array and a scalar;
167. bitwise_not(cvNot):inverts every bit of an array;
168. bitwise_xor(cvXor):calculates the per-elementbit-wise “exclusive of” operation on two arrays or an array and a scalar;
169. erode(cvErode):erodes an image by using a specificstructuring element;
170. dilate(cvDilate):dilates an image by using aspecific structuring element;
171. min(cvMin):calculates per-element minimum oftwo arrays or an array and a scalar;
172. max(cvMax):calculates per-element maximum oftwo arrays or an array and a scalar;
173. add(cvAdd):calculates the per-element sum oftwo arrays or an array and a scalar;
174. addWeighted(cvAddWeighted):calculates the weighted sum of twoarrays;
175. scaleAdd(cvScaleAdd):calculats the sum of a scaledarray and another array;
176. saturate_cast():template function for accurateconversion from one primitive type to another;
177. sqrt(cvSqrt):calculates a square root of arrayelements;
178. pow(cvPow):raises every array element to apower;
179. abs:calculates an absolute value ofeach matrix element;
180. convertScaleAbs(cvConvertScaleAbs):scales, calculates absolutevalues, and converts the result to 8-bit;
181. cuberoot(cvCbrt):computes the cube root of anargument;
182. exp(cvExp):calculates the exponent of everyarray element;
183. log(cvLog):calculates the natural logarithmof every array element;
184. Canny(cvCanny):finds edges in an image using theCanny algorithm;
185. Sobel(cvSobel):calculates the first, second,third, or mixed image derivatives using an extended Sobel operator;
186. Scharr:Calculates the first x – or y –image derivative using Scharr operator(Scharr 滤波器);
187. Laplacian(cvLaplace):calculates the Laplacian of animage;
188. getDerivKernels:returns filter coefficients forcomputing spatial image derivatives;
189. contourArea(cvContourArea):calculates a contour area;
190. LUT(cvLUT):performs a look-up table transformof an array;
191. calcBackProject(cvCalcBackProject):calculates the back projection ofa histogram(反向投影);
192. arcLength(cvArcLength):calculates a contour perimeter ora curve length;
193. meanShift(cvMeanShift):finds an object on a backprojection image;
194. CamShift(cvCamShift):finds an object center, size, andorientation;
195. TermCriteria:template class definingtermination criteria for iterative algorithms;
196. createTrackbar(cvCreateTrackbar):creates a trackbar and attaches itto the specified window;
197. watershed(cvWatershed):performs a marker-based imagesegmentation using the watershed algorithm;
198. grabCut:runs the GrabCut algorithm;
199. compare(cvCmp):performs the per-elementcomparison of two arrays or an array and scalar value;
200. mean(cvAvg):calculates an average(mean) ofarray elements;
201. meanStdDev(cvAvgSdv):calculates a mean and standarddeviation of array elements;
202. cartToPolar(cvCartToPolar):calculates the magnitude and angleof 2D vectors;
203. moments(cvMoments):calculates all of the moments upto the third order of a polygon or rasterized shape;
204. matchShapes(cvMatchShapes):compares two shapes;
205. cornerHarris(cvCornerHarris):Harris edge detector;
206. goodFeaturesToTrack(cvGoodFeaturesToTrack):determines strong corners on an image;
207. classFeatureDetector:abstract base class for 2D imagefeature detectors;
208. classFastFeatureDetector:wrapping class for featuredetection using the FAST() method;
209. classSURF(SurfFeatureDetector、SurfDescriptorExtractor):extracting Speeded Up Robust Featuresfrom an image;
210. classSIFT(SiftFeatureDetector):extracting keypoints and computingdescriptors using the Scale Invariant Feature Transform(SIFT) algorithm;
211. SURF::operator(cvExtractSURF):detects keypoints and computesSURF descriptors for them;
212. drawKeypoints:draw keypoints;
213. drawMatches:draws the found matches ofkeypoints from two images;
214. classDescriptorMatcher:abstract base class for matchingkeypoint descriptors. It has two groups of match methods,for matchingdescriptors of an image with another image or with an image set;
215. findChessboardCorners(cvFindChessboardCorners):finds the positions of internalcorners of the chessboard;
216. drawChessboardCorners(cvDrawChessboardCorners):renders the detected chessboardcorners;
217. calibrateCamera(cvCalibrateCamera2):finds the camera intrinsic andextrinsic parameters from several view of a calibration pattern;
218. initUndistortRectifyMap(cvInitUndistortMap、cvInitUndistortRectifyMap):computes the undistortion andrectification transformation map;
219. remap(cvRemap):applies a generic geometricaltransformation to an image;
220. calibrationMatrixValues:computes useful cameracharacteristics from the camera matrix;
221. findFundamentalMat(cvFindFundamentalMat):calculates a fundamental matrixfrom the corresponding points in two images;
222. computeCorrespondEpilines(cvComputeCorrespondEpilines):for points in an image of a stereopair, computes the corresponding epilines in the other image;
223. findHomography(cvFindHomography):finds a perspective transformationbetween two planes;
224. warpPerspective(cvWarpPerspective):applies a perspectivetransformation to an image;
225. getPerspectiveTransform(cvGetPerspectiveTransform):calculates a perspective transformfrom four pairs of the corresponding points;
226. cornerSubPix(cvFindCornerSubPix):refines the corner locations;
227. calcOpticalFlowPyrLK(cvCalcOpticalFlowPyrLK):calculates an optical flow for asparse feature set using the iterative Lucas-Kanade method with pyramids;
228. swap:swaps two matrices;
229. accumulateWeighted(cvRunningAvg):updates a running average;
230. classBackgroundSubtractorMOG:gaussian mixture-basedbackground/foreground segmentation algorithm;
231. randu:generates a singleuniformly-distributed(均匀分布) random number or an array ofrandom numbers;
232. randn:fills the array with normallydistributed(正态分布) random numbers;
233. getTickCount:returns the number of ticks;
234. getTickFrequency:returns the number of ticks persecond(使用getTickCount和getTickFrequency两个函数可以计算执行某个算法所用时间);
235. CV_Assert:checks a condition at runtime andthrows exception if it fails;
236. saturate_cast:template function for accurateconversion from one primitive type to another;
237. classRNG:random number generator;
238. RNG::next:returns the next random number;
239. RNG::operatorT:returns the next random number ofthe specified type;
240. RNG::operator():returns the next random number;
241. RNG::uniform:returns the next random numbersampled from the uniform distribution;
242. RNG::gaussian:returns the next random numbersampled from the Gaussian distribution;
243. RNG::fill:fills arrays with random numbers;
244. getOptimalDFTSize(cvGetOptimalDFTSize):returns the optimal DFT size for agiven vector size;
245. copyMakeBorder(cvCopyMakeBorder):forms a border around an image;
246. dft(cvDFT):performs a forward or inverseDiscrete Fourier transform of a 1D or 2D floating-point array;
247. magnitude:calculates the magnitude(幅度) of 2D vectors;
248. classFileStorage:XML/YAML file storage class thanencapsulates all the information necessary for writing or reading data to/froma file;
249. FileStorage::open:open a file;
250. FileStorage::isOpened:checks whether the file is opened;
251. FileStorage::release:closes the file and releases allthe memory buffers;
252. FileStorage::releaseAndGetString:closes the file and releases allthe memory buffers;
253. FileStorage::getFirstTopLevelNode:returns the first element of thetop-level mapping;
254. FileStorage::root:returns the top-level mapping;
255. FileStorage::operator[]:returns the specified element ofthe top-level mapping;
256. FileStorage::operator*:returns the obsolete C FileStorage structure;
257. FileStorage::writeRaw:writes multiple numbers;
258. FileStorage::writeObj:writes the registered C structure(CvMat、CvMatND、CvSeq);
259. FileStorage::getDefaultObjectName:returns the normalized object name for thespecified name of a file;
260. getAffineTransform(cvGetAffineTransform):calculates an affine transformfrom three pairs of the corresponding points;
261. getRotationMatrix2D(cv2DRotationmatrix):calculates an affine matrix of 2Drotation;
262. warpAffine(cvWarpAffine):applies an affine transformationto an image;
263. matchTemplate(cvMatchTemplate):compares a template against overlapped imageregions;