• Generate transparent shape on image


    Here is an example code to generate transparent shape on image. Need to pay attention can not use cv::Mat mask(mat) to create the mask image, because mask will be just a shallow copy of mat.

    int GenerateTransparentMask()
    {
        Mat mat = imread("test.jpg");
        if (mat.empty())
            return -1;
    
        Size size = mat.size();
        cv::Mat mask ( size, mat.type() );
        mat.copyTo(mask);
    
        //cv::Mat mask(mat);    //Can not work, becuase mask will be just a copy of mat, if draw on mask, means draw on mat too
    
        Rect rect(100, 100, 100, 100);
        rectangle(mask, rect, Scalar(0, 0, 255), CV_FILLED, CV_AA, 0);
    
        double alpha = 0.3;
        double beta = 1.0 - alpha;
        cv::addWeighted(mask, alpha, mat, beta, 0.0, mat);
    
        cvNamedWindow("Result");
        imshow("Result", mat);
    
        cvWaitKey(0); //wait for a key press
        return 0;
    }

     The result will as below: 

    If you need to generate complicated mask on an image, need to use a little different method. Below is the example code.

    int GenerateTransparentMask()
    {
        const Mat mat = imread("DetectingContours.jpg");
        if (mat.empty())
            return -1;
    
        imshow("origianl", mat);
    
        Size size = mat.size();
        cv::Mat copy ( size, mat.type() );
        mat.copyTo ( copy );
    
        //cv::Mat mask(mat);    //Can not work, becuase mask will be just a copy of mat, draw on mask, means draw on mat too
    
        cv::Mat mask(size, CV_8U);  //mask must be CV_8U
        mask.setTo(Scalar(0));
        Rect rect(200, 100, 200, 200);
        rectangle(mask, rect, Scalar(255, 255, 255), CV_FILLED, CV_AA, 0);
        rectangle(mask, Rect(280, 120, 40, 40), Scalar(0, 0, 0), CV_FILLED);
        circle(mask, Point(300, 220), 30, Scalar(0), CV_FILLED);
    
        copy.setTo(Scalar(0, 0, 255), mask);
        //imshow("copy", copy);
    
        double alpha = 0.5;
        double beta = 1.0 - alpha;
    
        cv::Mat result(size, mat.type());
        cv::addWeighted(copy, alpha, mat, beta, 0.0, result);
    
        cvNamedWindow("Result");
        imshow("Result", result);
    
        cvWaitKey(0); //wait for a key press
        return 0;
    }

  • 相关阅读:
    Odometer使用JavaScript和CSS制作数字滑动效果
    50个必备的实用jQuery代码段
    优化移动体验的HTML5技巧
    20 个非常棒的jQuery内容滑动插件
    最全的js正则表达式用法大全
    大神都未必解决的了简单问题,关于文字左右两端对齐。
    盘点20款表现出众的HTML5游戏
    蓝桥杯 格子问题:输出同行同列同对角线格子的位置
    与曹学长的一番谈话
    21天学习活动之——我的讲课新体验
  • 原文地址:https://www.cnblogs.com/shengguang/p/5240548.html
Copyright © 2020-2023  润新知