opencv 实现绿幕背景 视频抠图

在这里插入图片描述

#include <QCoreApplication>
#include "opencv2/opencv.hpp"

using namespace cv;
using namespace std;
const char* title="input video";
const char* resultWin="result voide";

Mat background_01;
 Mat replace_and_blend(Mat &frame,Mat &mask);
//视频抠图
int  main()
{
    background_01=imread("../image/1115.jpg");
    if(background_01.empty())
    {
        printf("could not load image ...");
        return ;
    }

    VideoCapture capture;
   // capture.open("../image/1113.jpg")
      capture.open(0);
    if(!capture.isOpened())
    {

         printf("could not load video ...");
         return;
    }
    int nCount=0;
    Mat frame,hsv,mask;
    while (capture.read(frame))
    {

        cvtColor(frame,hsv,CV_BGR2HSV);
        inRange(hsv,Scalar(35,44,46),Scalar(155,255,255),mask);
        //形态学操作
        Mat kernel=getStructuringElement(MORPH_RECT,Size(3,3),Point(-1,-1));
        morphologyEx(mask,mask,MORPH_CLOSE,kernel);

        erode(mask,mask,kernel);
        GaussianBlur(mask,mask,Size(3,3),0,0);

        Mat result=replace_and_blend(frame,mask);

        char c=waitKey(1);
        if(c==27)
        {
            break;
        }
        imshow("mask",mask);
        imshow("result",result);

        imshow(title,frame);

    }	
	return 0;
}

Mat replace_and_blend(Mat &frame,Mat &mask)
{

    Mat reslut=Mat::zeros(frame.size(),frame.type());
    int h=frame.rows;
    int w=frame.cols;
    int dims=frame.channels();

    //feplace and blend

    int m=0;
    double wt=0;
    int r=0,g=0,b=0;
    int r1=0,g1=0,b1=0;
    int r2=0,g2=0,b2=0;

    for (int row=0;row<h;row++)
    {
        uchar *current=frame.ptr<uchar>(row);
        uchar *bgrow=background_01.ptr<uchar>(row);
        uchar *maskrow=mask.ptr<uchar>(row);
        uchar *targetrow=reslut.ptr<uchar>(row);

        for (int col=0;col<w;col++)
        {
            m = *maskrow++;
            if(m==255)//背景
            {
                *targetrow++ = *bgrow++;
                *targetrow++ = *bgrow++;
                *targetrow++ = *bgrow++;
                current +=3;
            }
            else if (m==0) {//前景
                *targetrow++ = *current++;
                *targetrow++ = *current++;
                *targetrow++ = *current++;
                bgrow +=3;
            }
            else {
                b1 = *bgrow++;
                g1 = *bgrow++;
                r1 = *bgrow++;

                b2 = *current++;
                g2 = *current++;
                r2 = *current++;

                //权重
                wt=m/255.0;
                //混合
                b=b1*wt + b2*(1.0-wt);
                g=g1*wt + g2*(1.0-wt);
                 r=r1*wt + r2*(1.0-wt);

                 *targetrow++=b;
                 *targetrow++=g;
                 *targetrow++=r;
            }
        }

    }

    return  reslut;
}

在这里插入图片描述在这里插入图片描述

相关推荐
©️2020 CSDN 皮肤主题: 岁月 设计师:pinMode 返回首页