程序:

混合两个图像的一部分

关键函数:

cvSetImageROI

cvResetImageROI

cvAddWeighted

效果:

wKioL1PsZi3gTUpvAADOBw9H04s075.jpg

程序:

#include "cv.h"
#include "cxcore.h"
#include "highgui.h"
#include <iostream>
void MixPicture(IplImage* src1,IplImage* src2,int Src1x,int Src1y,int Src2x,int Src2y,int width,int height,double alpha)
{
CvRect ROIRect1=cvRect(Src1x,Src1y,width,height);
CvRect ROIRect2=cvRect(Src2x,Src2y,width,height);
cvSetImageROI(src1,ROIRect1);  //设置图像1的感兴趣区域
cvSetImageROI(src2,ROIRect2);
cvAddWeighted(src1,alpha,src2,1-alpha,0,src1);  //按照权重混合两个图像(只操作感兴趣区域)
cvResetImageROI(src1);   //释放图像1的感兴趣区域,要不显示的时候只会显示感兴趣区域
cvResetImageROI(src2);
}
void MixPicture_widthstep(IplImage* src1,IplImage* src2,int Src1x,int Src1y,int Src2x,int Src2y,int width,int height,double alpha)
{
for(int rows=0;rows<height;rows++)
{
uchar* Src1Ptr=(uchar*)(src1->p_w_picpathData+(Src1y+rows)*src1->widthStep); //注意是widthStep而不是width,因为可能有冗余字节
uchar* Src2Ptr=(uchar*)(src2->p_w_picpathData+(Src2y+rows)*src2->widthStep);
for(int cols=0;cols<width;cols++)
{
*(uchar*)(Src1Ptr+(Src1x+cols)*src1->nChannels)=(*(uchar*)(Src2Ptr+(Src2x+cols)*src2->nChannels))*(1-alpha)+(*(uchar*)(Src1Ptr+(Src1x+cols)*src1->nChannels))*alpha;
*(uchar*)(Src1Ptr+(Src1x+cols)*src1->nChannels+1)=(*(uchar*)(Src2Ptr+(Src2x+cols)*src2->nChannels+1))*(1-alpha)+(*(uchar*)(Src1Ptr+(Src1x+cols)*src1->nChannels+1))*alpha;
*(uchar*)(Src1Ptr+(Src1x+cols)*src1->nChannels+2)=(*(uchar*)(Src2Ptr+(Src2x+cols)*src2->nChannels+2))*(1-alpha)+(*(uchar*)(Src1Ptr+(Src1x+cols)*src1->nChannels+2))*alpha;
}
}
}
int ROI(int argc,char** argv)
{
IplImage* src1=cvLoadImage("e:\\picture\\3.jpg");
cvNamedWindow("src1");
cvShowImage("src1",src1);
IplImage* src2=cvLoadImage("e:\\picture\\11.jpg");
cvNamedWindow("src2");
cvShowImage("src2",src1);
//MixPicture(src1,src2,300,300,300,300,200,200,0.4);
MixPicture_widthstep(src1,src2,300,300,300,300,200,200,0.4);
cvNamedWindow("dst");
cvShowImage("dst",src1);
cvWaitKey(0);
cvDestroyWindow("src1");
cvDestroyWindow("src2");
cvDestroyWindow("dst");
cvReleaseImage(&src1);
cvReleaseImage(&src2);
return 0;
}