During the National Day holiday, I found that many friends changed their profile pictures, adding the effect of the national flag, becoming more festive.

The effect looks easy and can be achieved with just a few dozen lines of OpenCV.

The simplest version of image fusion

For the simplest version of image fusion, find an image and a picture of a standard flag. Crop the image to match the size of the flag.

Then, the two images are superimposed

    cv::Mat image = cv::imread("/Users/tony/Downloads/icon.jpg");
    cv::Mat flag = cv::imread("/Users/tony/Downloads/flag.png");
    cv::Mat roi,dst;
    cv::imshow("image",image);
    cv::imshow("flag",flag);

    roi = image(cv::Rect(300.400, flag.cols, flag.rows));

    cv::addWeighted(roi, 0.8, flag, 0.35.0, dst);
    cv::imshow("dst",dst);
Copy the code

The gradient version

Ok, so let’s try the gradient version again. The closer to the red flag, the greater the weight of the red flag. This will allow for a gradient effect.

    cv::Mat image = cv::imread("/Users/tony/Downloads/icon.jpg");
    cv::Mat flag = cv::imread("/Users/tony/Downloads/flag.png");

    int flag_width = flag.cols;
    int flag_height = flag.rows;

    Mat roi = image(cv::Rect(450.1200, flag_width, flag_height));

    int radius = 0;
    if (flag_width > flag_height) {
        radius = flag_width;
    } else {
        radius = flag_height;
    }

    for (int i=0; i<roi.rows; i++) {
        for (int j=0; j<roi.cols; j++) {int distance = std::sqrt(i*i+j*j);

            double alpha;
            if (distance > radius) {
                alpha =  1;
            }  else {
                alpha = (double) distance / radius;
            }

            Vec3b v1 = roi.at<Vec3b>(i,j);
            roi.at<Vec3b>(i,j)[0]=alpha*v1[0] + (1-alpha)*flag.at<Vec3b>(i,j)[0];
            roi.at<Vec3b>(i,j)[1]=alpha*v1[1] + (1-alpha)*flag.at<Vec3b>(i,j)[1];
            roi.at<Vec3b>(i,j)[2]=alpha*v1[2] + (1-alpha)*flag.at<Vec3b>(i,j)[2];
        }
    }

    cv::imshow("dst",roi);
Copy the code

This time, the effect is much better than the first time :). BTW, HAPPY National Day to you all!