opencv 绘制半透明图形

初学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);
}

然而受ROI只能设置为矩形的限制,如果我想绘制其他形状比如圆形改怎么办呢,其实只要3行代码就可以搞定了:复制原图,在新图上绘制,与原图加权叠加。代码如下:

#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;
}

当然这样也会带来不必要的开销,即不加以区别的对所有像素点都进行了加权计算,应该可以通过设置ROI来改善。


你可能感兴趣的:(opencv)