opencv常用函数(c++版本)

来源:互联网 发布:薄暮知秋什么意思 编辑:程序博客网 时间:2024/05/29 03:46

 
Mat

2001年刚刚出现的时候,OpenCV基于 C 语言接口而建。为了在内存(memory)中存放图像,当时采用名为 IplImage 的C语言结构体,时至今日这仍出现在大多数的旧版教程和教学材料。但这种方法必须接受C语言所有的不足,这其中最大的不足要数手动内存管理,其依据是用户要为开辟和销毁内存负责。虽然对于小型的程序来说手动管理内存不是问题,但一旦代码开始变得越来越庞大,你需要越来越多地纠缠于这个问题,而不是着力解决你的开发目标。

幸运的是,C++出现了,并且带来类的概念,这给用户带来另外一个选择:自动的内存管理(不严谨地说)。这是一个好消息,如果C++完全兼容C的话,这个变化不会带来兼容性问题。为此,OpenCV2.0版本中引入了一个新的C++接口,利用自动内存管理给出了解决问题的新方法。使用这个方法,你不需要纠结在管理内存上,而且你的代码会变得简洁(少写多得)。但C++接口唯一的不足是当前许多嵌入式开发系统只支持C语言。所以,当目标不是这种开发平台时,没有必要使用 旧 方法(除非你是自找麻烦的受虐狂码农)。

关于 Mat ,首先要知道的是你不必再手动地(1)为其开辟空间(2)在不需要时立即将空间释放。但手动地做还是可以的:大多数OpenCV函数仍会手动地为输出数据开辟空间。当传递一个已经存在的 Mat 对象时,开辟好的矩阵空间会被重用。也就是说,我们每次都使用大小正好的内存来完成任务。

基本上讲 Mat 是一个类,由两个数据部分组成:矩阵头(包含矩阵尺寸,存储方法,存储地址等信息)和一个指向存储所有像素值的矩阵(根据所选存储方法的不同矩阵可以是不同的维数)的指针。矩阵头的尺寸是常数值,但矩阵本身的尺寸会依图像的不同而不同,通常比矩阵头的尺寸大数个数量级。因此,当在程序中传递图像并创建拷贝时,大的开销是由矩阵造成的,而不是信息头。OpenCV是一个图像处理库,囊括了大量的图像处理函数,为了解决问题通常要使用库中的多个函数,因此在函数中传递图像是家常便饭。同时不要忘了我们正在讨论的是计算量很大的图像处理算法,因此,除非万不得已,我们不应该拷贝 大 的图像,因为这会降低程序速度。

为了搞定这个问题,OpenCV使用引用计数机制。其思路是让每个 Mat 对象有自己的信息头,但共享同一个矩阵。这通过让矩阵指针指向同一地址而实现。而拷贝构造函数则 只拷贝信息头和矩阵指针 ,而不拷贝矩阵

 

C++版本

好处:

1、在于可以尽量避免使用指针这种危险的东西;

2、不用费心去release资源了,因为在其destructor里面,系统会自动帮你搞定。

3、在某些情况下会比C版本运行速度快。

在文件中包含 using namespace cv;

可以移植到硬件上,如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.


image – Image to be shown.


The function imshow displays an image in the specified window. If the window was created with the CV_WINDOW_AUTOSIZE flag, 

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::isOpenedreturns 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::openinitializes or reinitializes videowriter

25.    VideoWriter::isOpenedreturns true if video writer hasbeen successfully initialized

26.    VideoWriter::writewrites the next video frame

27.    Mat::rowcreates a matrix header for thespecified matrix row

28.    Mat::colcreates a matrix header for thespecified matrix column

29.    Mat::rowRangecreates a matrix header for thespecified row span

30.    Mat::colRangecreates a matrix header for thespecified col span

31.    Mat::diagextracts a diagonal from a matrix,or creates a diagonal matrix

32.    Mat::clonecreates 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::assignToprovides a functional form ofconvertTo

36.    Mat::setTosets all or some of the arrayelements to the specified value

37.    Mat::reshapechanges the shape and/or thenumber of channels of a 2D matrix without copying the data

38.    Mat::ttransposes a matrix

39.    Mat::invinverses a matrix

40.    Mat::mulperforms an element-wisemultiplication or division of the two matrices

41.    Mat::crosscomputes a cross-product of two3-element vectors

42.    Mat::dotcomputes a dot-product of twovectors

43.    Mat::zerosreturns a zero array of thespecified size and type

44.    Mat::onesreturns an array of all 1s of thespecified size and type

45.    Mat::eyereturns an identity matrix of thespecified size and type

46.    Mat::createallocates new array data if needed

47.    Mat::addrefincrements the reference counter

48.    Mat::releasedecrements the reference counterand deallocates the matrix if needed

49.    Mat::resizechanges the number of matrix rows

50.    Mat::reservereserves space for the certainnumber of rows

51.    Mat::push_backadds elements to the bottom of thematrix

52.    Mat::pop_backremoves elements from the bottomof the matrix

53.    Mat::locateROIlocates the matrix header within aparent matrix

54.    Mat::adjustROIadjusts a submatrix size andposition within the parent matrix

55.    Mat::operatorextracts a rectangular submatrix

56.    Mat::operatorCvMatcreates the CvMat header for thematrix

57.    Mat::operatorIplImagecreates the IplImage header forthe matrix

58.    Mat::totalreturns the total number fo arrayelements

59.    Mat::isContinuousreports whether the matrix iscontinuous or not

60.    Mat::elemSizereturns the matrix element size inbytes

61.    Mat::elemSize1returns the size of each matrixelement channel in bytes

62.    Mat::typereturns the type of a matrixelement

63.    Mat::depthreturns the depth of a matrixelement

64.    Mat::channelsreturns the number of matrix channels

65.    Mat::step1returns a normalized step

66.    Mat::sizereturns a matrix size

67.    Mat::emptyreturns true if the array has noelemens

68.    Mat::ptrreturns a pointer to the specifiedmatrix row

69.    Mat::atreturns a reference to thespecified array element

70.    Mat::beginreturns the matrix iterator andsets it to the first matrix element

71.    Mat::endreturns 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.    normalizenormalizes the norm or value rangeof an array

76.    CascadeClassifier::CascadeClassifierloads a classifier from a file

77.    CascadeClassifier::empthchecks whether the classifier hasbeen loaded

78.    CascadeClassifier::load(cvLoadHaarClassifierCascade)loads a classifier from a file

79.    CascadeClassifier::readreads 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.    groupRectanglesgroups 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.    bilateralFilterapplies the bilateral filter to animage(双边滤波)

89.    blur(cvSmooth)blurs an image using thenormalized box filter(均值模糊)

90.    medianBlurblurs an image using the medianfilter(中值模糊)

91.    boxFilterblurs an image using the boxfilter

92.    GaussianBlurblurs an image using a Gaussianfilter(高斯模糊)

93.    getGaussianKernelreturns Gaussian filtercoefficients

94.    sepFilter2Dapplies 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::getreturns the algorithm parameter

99.    Algorithm::setset the algorithm parameter

100. Algorithm::writestores algorithm parameters in afile storage

101. Algorithm::readreads algorithm parameters from afile storage

102. Algorithm::getListreturns the list of registeredalgorithms

103. Algorithm::createcreates algorithm instance by name

104. FaceRecognizer::traintrains a FaceRecognizer with givendata and associated labels

105. FaceRecognizer::updateupdates a FaceRecognizer withgiven data and associated labels

106. FaceRecognizer::predictpredicts a label and associatedconfidence(e.g. distance) for a given input image

107. FaceRecognizer::savesaves a FaceRecognizer and itsmodel state

108. FaceRecognizer::loadloads 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::CvSVMdefault and training constructors

122. CvSVM::traintrains an SVM

123. CvSVM::train_autotrains an SVM with optimalparameters

124. CvSVM::predictpredicts the response for inputsample(s)

125. CvSVM::get_default_gridgenerates a grid for SVMparameters

126. CvSVM::get_paramsreturns the current SVM parameters

127. CvSVM::get_support_vectorretrieves a number of supportvectors and the particular vector

128. CvSVM::get_var_countreturns thenumber of used features(variables count)

129. CvANN_MLP(multi-layerperceptrons)::CvANN_MLPthe constructors

130. CvANN_MLP::createconstructs MLP with the specifiedtopology

131. CvANN_MLP::traintrains/updates MLP

132. CvANN_MLP::predictpredicts responses for inputsamples

133. CvANN_MLP::get_layer_countreturns the number fo layers inthe MLP

134. CvANN_MLP::get_layer_sizereturns numbers of neurons in eachlayer of the MLP

135. CvANN_MLP::get_weightsreturns neurons weights of theparticular layer

136. CvKNearest::CvKNearestdefault and training constructors

137. CvKNearest::traintrains the model

138. CvKNearest::find_nearestfinds the neighbors and predictsresponses for input vectors

139. CvKNearest::get_max_kreturns the number of maximumneighbors that may be passed to the method CvKNearest::find_nearest()

140. CvKNearest::get_var_countreturns the number of usedfeatures(variables count)

141. CvKNearest::get_sample_countreturns the total number of trainsamples

142. CvKNearest::is_regressionreturns type of the problem(truefor regression and false for classification)

143. HoughLines(cvHoughLines)finds lines in a binary imageusing the standard Hough transform

144. HoughLinesPfinds 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(cvEllipsecvEllipseBox)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. fillPolyfills 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. abscalculates 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. ScharrCalculates the first x – or y image derivative using Scharr operator(Scharr 滤波器)

187. Laplacian(cvLaplace)calculates the Laplacian of animage

188. getDerivKernelsreturns 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. TermCriteriatemplate 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. grabCutruns 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. classFeatureDetectorabstract base class for 2D imagefeature detectors

208. classFastFeatureDetectorwrapping class for featuredetection using the FAST() method

209. classSURF(SurfFeatureDetectorSurfDescriptorExtractor)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. drawKeypointsdraw keypoints

213. drawMatchesdraws the found matches ofkeypoints from two images

214. classDescriptorMatcherabstract 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(cvInitUndistortMapcvInitUndistortRectifyMap)computes the undistortion andrectification transformation map

219. remap(cvRemap)applies a generic geometricaltransformation to an image

220. calibrationMatrixValuescomputes 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. swapswaps two matrices

229. accumulateWeighted(cvRunningAvg)updates a running average

230. classBackgroundSubtractorMOGgaussian mixture-basedbackground/foreground segmentation algorithm

231. randugenerates a singleuniformly-distributed(均匀分布) random number or an array ofrandom numbers

232. randnfills the array with normallydistributed(正态分布) random numbers

233. getTickCountreturns the number of ticks

234. getTickFrequencyreturns the number of ticks persecond(使用getTickCountgetTickFrequency两个函数可以计算执行某个算法所用时间)

235. CV_Assertchecks a condition at runtime andthrows exception if it fails

236. saturate_casttemplate function for accurateconversion from one primitive type to another

237. classRNGrandom number generator

238. RNG::nextreturns the next random number

239. RNG::operatorTreturns the next random number ofthe specified type

240. RNG::operator()returns the next random number

241. RNG::uniformreturns the next random numbersampled from the uniform distribution

242. RNG::gaussianreturns the next random numbersampled from the Gaussian distribution

243. RNG::fillfills 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. magnitudecalculates the magnitude(幅度) of 2D vectors

248. classFileStorageXML/YAML file storage class thanencapsulates all the information necessary for writing or reading data to/froma file

249. FileStorage::openopen a file

250. FileStorage::isOpenedchecks whether the file is opened

251. FileStorage::releasecloses the file and releases allthe memory buffers

252. FileStorage::releaseAndGetStringcloses the file and releases allthe memory buffers

253. FileStorage::getFirstTopLevelNodereturns the first element of thetop-level mapping

254. FileStorage::rootreturns 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::writeRawwrites multiple numbers

258. FileStorage::writeObjwrites the registered C structure(CvMatCvMatNDCvSeq)

259. FileStorage::getDefaultObjectNamereturns 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

 

0 0
原创粉丝点击