Question

I want to blend two images like multiply blending in photoshop , i want to do the same in OpenCv using C++ for my app , I visit this many time and try to understand every time but i didn't get it , i search it alot but didn't get what i want other then this but this is little bit strange as conversion is alot from IplImages to ibl etc , Any help , guide, idea and example related opencv is needed . I go through Addweight but i think its quite different from Multiply Blending

Formula which i saw here

Target * Blend

and below is what i tried

Mat img1 = imread("E:\\img.jpg");
Mat img2 = Mat (img1.size(),img1.type());
vector<Mat> colors_1;
split(img2, colors_1);
colors_1[0] = 113;
colors_1[1] = 221;
colors_1[2] = 216;
merge(colors_1,img2);
Mat result(img1.size(), CV_32F);
for(int i = 0; i < img1.size().height; ++i){
    for(int j = 0; j < img1.size().width; ++j){
        for (int rgb=0 ; rgb<=img1.channels();rgb++){
            float target = float(img1.at<uchar>(i, j)) / 255;
            float blend = float(img2.at<uchar>(i, j)) / 255;
            result.at<float>(i, j) = target*blend;
        }

    }
}  

Result is in GrayScale and its not looking exact

Thank you

Was it helpful?

Solution

You are not accessing the image channels correctly. Moreover, you do not need to store the result in a float image, uchar is OK. Also, your loop on RGB channels should end when rgb<img1.channels().

Try this code:

cv::Mat img1 = cv::imread("E:\\img.jpg");
cv::Mat img2 = cv::Mat (img1.size(),img1.type());
std::vector<cv::Mat> colors_1;
cv::split(img2, colors_1);
colors_1[0] = 113;
colors_1[1] = 221;
colors_1[2] = 216;
cv::merge(colors_1,img2);
cv::Mat result(img1.size(), CV_8UC3);
for(int i = 0; i < img1.rows; ++i){
    for(int j = 0; j < img1.cols; ++j){
        for (int c=0 ; c<img1.channels();c++){
            uchar target = img1.at<uchar>(i, 3*j+c);
            uchar blend = img2.at<uchar>(i, 3*j+c);
            result.at<uchar>(i, 3*j+c) = cv::saturate_cast<uchar>(target*blend/255.);
        }
    }
}  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top