源
初学OpenCV,想绘制半透明矩形,却发现没有GDI+那么简单,在网上搜寻了一番任未得其解,偶然翻到一个对两张图片进行像素值加权叠加的函数cvAddWeighted,于是参照例程加以改造写了一个绘制半透明矩形的封装方法:
void DrawTransRec(IplImage* img,int x,int y,int width,int height,CvScalar color,double alpha)
{
IplImage * rec=cvCreateImage(cvSize(width,height),img->depth,img->nChannels);
cvRectangle(rec,cvPoint(0,0),cvPoint(width,height),color,-1);
cvSetImageROI(img,cvRect(x,y,width,height));
cvAddWeighted(img,alpha,rec,1-alpha,0.0,img);
cvResetImageROI(img);
}
#include "stdafx.h"
#include
#include
void DrawTransRec(IplImage* img,int x,int y,int width,int height,CvScalar color,double alpha)
{
IplImage * rec=cvCreateImage(cvSize(width,height),img->depth,img->nChannels);
cvRectangle(rec,cvPoint(0,0),cvPoint(width,height),color,-1);
cvSetImageROI(img,cvRect(x,y,width,height));
cvAddWeighted(img,alpha,rec,1-alpha,0.0,img);
cvResetImageROI(img);
}
int _tmain(int argc, _TCHAR* argv[])
{
IplImage * pImage=cvLoadImage("1.jpg");
if(!pImage)
{
fprintf(stderr,"Can not open image filen");
return -1;
}
DrawTransRec(pImage,150,150,150,150,CV_RGB(255,0,0),0.5);
IplImage * pTemp=(IplImage*)cvClone(pImage);
cvCircle(pTemp,cvPoint(200,200),100,CV_RGB(255,0,0),-1);
cvAddWeighted(pImage,0.4,pTemp,0.6,0.0,pImage);
cvReleaseImage(&pTemp);
cvNamedWindow("OpenCVTest",1);
cvShowImage("OpenCVTest",pImage);
cvWaitKey();
cvDestroyWindow("OpenCVTest");
cvReleaseImage(&pImage);
return 0;
}