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文件。

相關文章
相關標籤/搜索