Ask Your Question

Revision history [back]

your question is a bit unclear but maybe this answer will give you new ideas...

take a look at https://answers.opencv.org/question/73016 and the code below

image description

image description

#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>

using namespace cv;
using namespace std;

void overlayImage(Mat* src, Mat* overlay, const Point& location)
{
    for (int y = max(location.y, 0); y < src->rows; ++y)
    {
        int fY = y - location.y;

        if (fY >= overlay->rows)
            break;

        for (int x = max(location.x, 0); x < src->cols; ++x)
        {
            int fX = x - location.x;

            if (fX >= overlay->cols)
                break;

            double opacity = ((double)overlay->data[fY * overlay->step + fX * overlay->channels() + 3]) / 255;

            for (int c = 0; opacity > 0 && c < src->channels(); ++c)
            {
                unsigned char overlayPx = overlay->data[fY * overlay->step + fX * overlay->channels() + c];
                unsigned char srcPx = src->data[y * src->step + x * src->channels() + c];
                src->data[y * src->step + src->channels() * x + c] = srcPx * (1. - opacity) + overlayPx * opacity;
            }
        }
    }
}

int main(int argc, char** argv)
{
    Mat underlay0 = imread("lena.jpg", IMREAD_UNCHANGED);
    Mat overlay = imread("opencv-logo-white.png", IMREAD_UNCHANGED);
    Mat underlay1 = underlay0.clone();

    if (underlay0.empty() || overlay.empty())
    {
        cout << "Could not read input image files " << endl;
        return -1;
    }

    overlayImage(&underlay0, &overlay, Point());
    imshow("result1", underlay0);

    overlay = overlay - Scalar(0, 0, 0, 127);

    overlayImage(&underlay1, &overlay, Point());
    imshow("result2", underlay1);

    waitKey();

    return 0;
}