源代码来源于官网的OpenCV教程,实现的功能比较简单最后自己动手用C语言实现了一下,貌似比库函数要快一点
- #include "StdAfx.h"
- #include "blending.h"
- using namespace std;
- using namespace cv;
- void blending_test()
- {
- Mat src1, src2, dst;
- double alpha = 0.5;
- double beta = 1-alpha;
- src1 = imread("LinuxLogo.jpg");
- src2 = imread("WindowsLogo.jpg");
- if(!src1.data) cout<<"error loading src1"<<endl;
- if(!src2.data) cout<<"Error loading src2"<<endl;
- addWeighted(src1, alpha, src2, beta, 0.0, dst);
- imshow("output1", dst);
- // waitKey(0);
- }
- //C语言自己实现
- void blending()
- {
- Mat src1, src2, dst;
- double alpha = 0.5;
- double beta = 1-alpha;
- double gama = 0;
- src1 = imread("LinuxLogo.jpg");
- src2 = imread("WindowsLogo.jpg");
- //判断两幅图片是否相同
- CV_Assert(src1.depth() == CV_8U);
- CV_Assert(src1.depth() == src2.depth());
- CV_Assert(src1.size() == src2.size());
- //为dst申请内存
- dst.create(src1.size(), src1.type());
- const int nChannels = src1.channels();
- if(!src1.data) cout<<"error loading src1"<<endl;
- if(!src2.data) cout<<"Error loading src2"<<endl;
- for (int i=0; i<src1.rows; i++)
- {
- const uchar* src1_ptr = src1.ptr<uchar>(i);
- const uchar* src2_ptr = src2.ptr<uchar>(i);
- uchar* dst_ptr = dst.ptr<uchar>(i);
- for (int j=0; j<src1.cols*nChannels; j++)
- {
- dst_ptr[j] = src1_ptr[j]*alpha + src2_ptr[j]*beta + gama;
- }
- }
- imshow("output2",dst);
- // cvWaitKey(0);
- }
- int main(int argc, char* argv[])
- {
- double t;
- t = (double)getTickCount();
- blending_test();
- t = 1000*((double)getTickCount() - t)/getTickFrequency();
- cout<<"库函数时间:"<<t<<endl;
- t = (double)getTickCount();
- blending();
- t = 1000*((double)getTickCount() - t)/getTickFrequency();
- cout<<"C语言实现:"<<t<<endl;
- cvWaitKey(0);
- return 0;
- }
//下面是运行的结果
注意了自己实现的没有数据溢出保护,关于saturate_cast的用法会在下个文章中讲解
http://blog.youkuaiyun.com/mjlsuccess/article/details/12401839