Home > Enterprise >  OpenCV: "draw" image on another image
OpenCV: "draw" image on another image

Time:11-06

I have 2 images with transparency. Images have the same format and size. How can I copy pixels from second image to the first one by using C OpenCV? The idea is to draw 2nd image on the 1st image.

Thanks

CodePudding user response:

code from the link in comment above (modified for my case) L. Scott Johnson thanks you again!

void alphaBlend(Mat& foreground, Mat& background, Mat& alpha, Mat& outImage)
{
    // Find number of pixels.
    int numberOfPixels = foreground.rows * foreground.cols * foreground.channels();

    // Get floating point pointers to the data matrices

    float* fptr = reinterpret_cast<float*>(foreground.data);
    float* bptr = reinterpret_cast<float*>(background.data);
    float* aptr = reinterpret_cast<float*>(alpha.data);
    float* outImagePtr = reinterpret_cast<float*>(outImage.data);


    // Loop over all pixesl ONCE

    for (
        int i = 0;
        i < numberOfPixels;
        i  , outImagePtr  , fptr  /*, aptr  */,  bptr  
        )
    {
        if (i!= 0 && (i % 3) == 0)
            aptr  ;

        *outImagePtr = (*fptr) * (*aptr)   (*bptr) * (1 - *aptr);
    }
}


void Mix()
{
    Mat layer = imread("images\\leyer.png", IMREAD_UNCHANGED);
    Mat image = imread("images\\bg.jpg");
    
    std::vector<cv::Mat> bgra_planes;
    cv::split(layer, bgra_planes);
    
    Mat alpha = bgra_planes[3];

    bgra_planes.pop_back();
    cv::merge(bgra_planes, layer);

    alpha.convertTo(alpha, CV_32FC3, 1.0 / 255);
    layer.convertTo(layer, CV_32FC3);
    image.convertTo(image, CV_32FC3);


    Mat result(layer.size(), CV_32FC3);

    alphaBlend(layer, image, alpha, result);

    result.convertTo(result, CV_8UC3);

    // previous tries
    //cv::copyTo(layer, image, );
    //cv::addWeighted(image, 1, layer, 1, 0.5, result);

    String windowName = "alpha blending"; 
    namedWindow(windowName, WINDOW_NORMAL); 
    imshow(windowName, result); 
    waitKey(0); 
    destroyWindow(windowName); 
}

CodePudding user response:

Here's what you can try:

load your first image

cv::Mat img = cv::imread("img.jpeg");

find your smaller image - here I'm just resizing the same image

cv::Mat img_resize;
cv::resize(img, img_resize, cv::Size(), 0.3, 0.3);

choose the xy origin location

const cv::Point origin(100, 100);

create a Region of Interest

cv::Rect roi(origin, img_resize.size());

copy the matrix data in

img_resize.copyTo(img(roi));
  • Related