OpenCV中的均值与最值的计算

来源:互联网 发布:淘宝挣钱 编辑:程序博客网 时间:2024/06/18 09:04

opencv Mat 求元素 中值 均值 总和

原创 2015年01月31日 21:50:11

搜索和很久,还是没有发现求mat 内元素的中值函数,于是自己写了一个


[cpp] view plain copy
  1. float Median_Mat_32f(Mat img)  
  2. {  
  3.     float *buf;  
  4.     buf = new float[img.rows*img.cols];  
  5.   
  6.     for (int i =0; i < img.rows; i++)  
  7.     {  
  8.         for (int j = 0; j < img.cols; j++)  
  9.         {  
  10.             buf[i*img.cols+j] = img.ptr<float>(i)[j];  
  11.         }  
  12.     }  
  13.     qsort(buf, 3, sizeof(buf[0]), comp);  
  14.     return buf[img.rows*img.cols/2];  
  15. }  

数据类型不确定,于是又想起了写一个模板

上代码:

[cpp] view plain copy
  1. //比较两数大小  
  2. template <typename _Tp>  
  3. int mem_cmp(const void *a, const void *b)    
  4. {    
  5.     //当_Tp为浮点型,可能由于精度,会影响排序  
  6.     return (*((_Tp *)a) - *((_Tp *)b));    
  7. }  
  8.   
  9. //求Mat元素中值  
  10. template <typename _Tp>  
  11. _Tp medianElem(Mat img)  
  12. {  
  13.     _Tp *buf;  
  14.     size_t total = img.total();  
  15.   
  16.     buf = new _Tp[total];  
  17.   
  18.     for (int i = 0; i < img.rows; i++)  
  19.     {    
  20.         for (int j = 0; j < img.cols; j++)  
  21.         {    
  22.             buf[i*img.cols+j] = img.ptr<_Tp>(i)[j];    
  23.         }    
  24.     }  
  25.   
  26.     qsort(buf, total, sizeof(_Tp), mem_cmp<_Tp>);  
  27.   
  28.     return buf[total/2];  
  29. }  

 

[cpp] view plain copy
  1. //求Mat元素总和(单通道)  
  2. template <typename _Tp>  
  3. double sumElem(Mat img)  
  4. {  
  5.     double sum = 0;  
  6.   
  7.     for (int i = 0; i < img.rows; i++)  
  8.     {    
  9.         for (int j = 0; j < img.cols; j++)  
  10.         {    
  11.             sum += img.ptr<_Tp>(i)[j];    
  12.         }    
  13.     }  
  14.   
  15.     return sum;  
  16. }  
  17.   
  18. //求Mat元素均值(单通道)  
  19. template <typename _Tp>  
  20. _Tp sumElem(Mat img)  
  21. {  
  22.     return _Tp(sumElem<_Tp>(img)/img.total());  
  23. }  



原创粉丝点击