zoukankan      html  css  js  c++  java
  • 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;
    }

  • 相关阅读:
    NavigationBar隐藏
    (4)通过调用hadoop的java api实现本地文件上传到hadoop文件系统上
    Makefile 中:= ?= += =的差别 和条件运行
    C# 使用WinRar命令压缩和解压缩
    C# 字段、属性、成员变量
    js中推断对象详细类型
    Python学习入门基础教程(learning Python)--3.3.3 Python逻辑关系表达式
    JavaScript类数组对象参考
    Codeforces Round 190 div.2 322C 321A Ciel and Robot
    Android Application plugin
  • 原文地址:https://www.cnblogs.com/shengguang/p/5240548.html
Copyright © 2011-2022 走看看