OpenCV 1.0 & 2.0 cvtexture.cpp bug 修正 内存分配错误

最近项目须要提取图像特征:能量、熵、对比度等等,以对视野当前状态进行简单分类。php

发现OpenCV上有cvtexture文件,有可用信息。但对其进行调试以后发现,存在一些问题。查阅后,参照http://www.opencv.org.cn/forum/viewtopic.php?f=10&t=8379&p=44545&hilit=cvtexture&sid=eec47a63b50b8e7f07d6fee4030fae8a#p44545进行了简单修改。修改后,问题获得解决,可是感受结果不对,而且出现内存错误的缘由不多是因为malloc和new的关系。数组

对原始cvTexture.cpp调试以后,发现问题停在函数 icvCreateGLCM_LookupTable_8u_C1R ,感受是内存分配越界问题。ide

浏览代码后,发下以下几个问题:函数

1. 函数 cvCreateGLCM 中,在动态建立CvGLCM结构体时:oop

  1. CV_CALL( newGLCM = (CvGLCM*)cvAlloc(sizeof(newGLCM)));  
  2. memset( newGLCM, 0, sizeof(newGLCM) );  

CV_CALL( newGLCM = (CvGLCM*)cvAlloc(sizeof(newGLCM))); memset( newGLCM, 0, sizeof(newGLCM) );  

很明显 对动态申请的内存 存在错误, 改动以下:spa

  1. CV_CALL( newGLCM = (CvGLCM*)cvAlloc(sizeof(CvGLCM)));  
  2. memset( newGLCM, 0, sizeof(CvGLCM) );  

CV_CALL( newGLCM = (CvGLCM*)cvAlloc(sizeof(CvGLCM))); memset( newGLCM, 0, sizeof(CvGLCM) );调试

 

2. 函数icvCreateGLCM_LookupTable_8u_C1R中,建立三维数组时:ip

  1. CV_CALL( matrices[stepLoop] = (double**)cvAlloc( sizeof(matrices[0])*matrixSideLength ));  
  2. CV_CALL( matrices[stepLoop][0] = (double*)cvAlloc( sizeof(matrices[0][0])*                                                 matrixSideLength*matrixSideLength ));  
  3. memset( matrices[stepLoop][0], 0, matrixSideLength*matrixSideLength*                                         sizeof(matrices[0][0]) );  

CV_CALL( matrices[stepLoop] = (double**)cvAlloc( sizeof(matrices[0])*matrixSideLength )); CV_CALL( matrices[stepLoop][0] = (double*)cvAlloc( sizeof(matrices[0][0])* matrixSideLength*matrixSideLength )); memset( matrices[stepLoop][0], 0, matrixSideLength*matrixSideLength* sizeof(matrices[0][0]) );内存

 

建立的一维二维数组,cvAlloc的大小都存在问题。更正以下:get

  1. CV_CALL( matrices[stepLoop] = (double**)cvAlloc( sizeof(matrices[0][0])*matrixSideLength ));  
  2. CV_CALL( matrices[stepLoop][0] = (double*)cvAlloc( sizeof(matrices[0][0][0])*matrixSideLength*matrixSideLength ));  
  3.           
  4. memset( matrices[stepLoop][0], 0, matrixSideLength*matrixSideLength*sizeof(matrices[0][0][0]) );  

CV_CALL( matrices[stepLoop] = (double**)cvAlloc( sizeof(matrices[0][0])*matrixSideLength )); CV_CALL( matrices[stepLoop][0] = (double*)cvAlloc( sizeof(matrices[0][0][0])*matrixSideLength*matrixSideLength )); memset( matrices[stepLoop][0], 0, matrixSideLength*matrixSideLength*sizeof(matrices[0][0][0]) );

 

3. 在函数icvCreateGLCMDescriptors_AllowDoubleNest中使用cvAlloc申请内存,但使用delete[]释放内存,出现错误。

更正以下:

  1. //delete [] marginalProbability;  
  2. cvFree(&marginalProbability);  

//delete [] marginalProbability; cvFree(&marginalProbability);

 

修正以上三项以后,程序能够获得结果,可是结果的正确性没有验证。

另外,对文件修改完成后,若是新工程没有和OpenCV工程创建依赖关系,须要对OpenCV工程从新编译,生成新的DLL文件。