OpenCV学习--saturate_cast防止数据溢出

来源:互联网 发布:阿尔法软件使用视频 编辑:程序博客网 时间:2024/05/01 01:03

源代码来源于官网的OpenCV教程,实现的功能比较简单最后自己动手用C语言实现了一下,貌似比库函数要快一点大笑

[cpp] view plaincopy
  1. #include "StdAfx.h"  
  2. #include "blending.h"  
  3. using namespace std;  
  4. using namespace cv;  
  5. void blending_test()  
  6. {  
  7.     Mat src1, src2, dst;  
  8.     double alpha = 0.5;  
  9.     double beta = 1-alpha;  
  10.   
  11.     src1 = imread("LinuxLogo.jpg");  
  12.     src2 = imread("WindowsLogo.jpg");  
  13.   
  14.     if(!src1.data) cout<<"error loading src1"<<endl;  
  15.     if(!src2.data) cout<<"Error loading src2"<<endl;  
  16.   
  17.     addWeighted(src1, alpha, src2, beta, 0.0, dst);  
  18.   
  19.     imshow("output1", dst);  
  20.   
  21. //  waitKey(0);  
  22. }  
  23. //C语言自己实现  
  24. void blending()  
  25. {  
  26.     Mat src1, src2, dst;  
  27.     double alpha = 0.5;  
  28.     double beta = 1-alpha;  
  29.     double gama = 0;  
  30.   
  31.     src1 = imread("LinuxLogo.jpg");  
  32.     src2 = imread("WindowsLogo.jpg");  
  33.     //判断两幅图片是否相同  
  34.     CV_Assert(src1.depth() == CV_8U);  
  35.     CV_Assert(src1.depth() == src2.depth());  
  36.     CV_Assert(src1.size() == src2.size());  
  37.     //为dst申请内存  
  38.     dst.create(src1.size(), src1.type());  
  39.   
  40.     const int nChannels = src1.channels();  
  41.   
  42.     if(!src1.data) cout<<"error loading src1"<<endl;  
  43.     if(!src2.data) cout<<"Error loading src2"<<endl;  
  44.   
  45.     for (int i=0; i<src1.rows; i++)  
  46.     {  
  47.         const uchar* src1_ptr = src1.ptr<uchar>(i);  
  48.         const uchar* src2_ptr = src2.ptr<uchar>(i);  
  49.         uchar* dst_ptr  = dst.ptr<uchar>(i);  
  50.         for (int j=0; j<src1.cols*nChannels; j++)  
  51.         {  
  52.             dst_ptr[j] = src1_ptr[j]*alpha + src2_ptr[j]*beta + gama;  
  53.         }  
  54.     }  
  55.     imshow("output2",dst);  
  56.   
  57. //  cvWaitKey(0);  
  58. }  
//下面是main函数部分
[cpp] view plaincopy
  1. int main(int argc, char* argv[])   
  2. {   
  3.     double t;  
  4.     t = (double)getTickCount();   
  5.     blending_test();      
  6.     t = 1000*((double)getTickCount() - t)/getTickFrequency();  
  7.     cout<<"库函数时间:"<<t<<endl;  
  8.   
  9.     t = (double)getTickCount();  
  10.     blending();  
  11.     t = 1000*((double)getTickCount() - t)/getTickFrequency();  
  12.     cout<<"C语言实现:"<<t<<endl;  
  13.   
  14.     cvWaitKey(0);  
  15.     return 0;  
  16. }  

//下面是运行的结果

注意了自己实现的没有数据溢出保护,关于saturate_cast的用法会在下个文章中讲解

http://blog.csdn.net/mjlsuccess/article/details/12401839

0 0
原创粉丝点击