TheAddWeighted function throws an exception.

asked 2016-01-21 15:32:04 -0500

The AddWeighted function in my code throws an exception anytime I try to add a logo to a main image using the Region-of-Interest method. I'm new to opencv and can't figure out why. I've also tried a couple of images, all ending in the same way.

/*
 * main.cpp
 *
 *  Created on: 19 Jan 2016
 *      Author: Aceix
 */


#include <iostream>
#include <string>

#include "opencv2/core.hpp"
#include "opencv2/highgui.hpp"


int main(){
    std::string imgLoc;

    std::cout<<"Enter main image location: ";
    std::cin>>imgLoc;

    cv::Mat mainImg{cv::imread(imgLoc)};
    if(mainImg.data){
        std::cout<<"\nEnter logo image location: ";
        std::cin>>imgLoc;

        cv::Mat logoImg{cv::imread(imgLoc)};
        if(logoImg.data){
            float scale=0.f;
            std::cout<<"\nEnter scale for combining logo: ";
            std::cin>>scale;
            if(scale > 1.f){
                scale = 1.f;
            }
            else if(scale<0.f){
                scale = 0.f;
            }

            int x(mainImg.cols - logoImg.cols + mainImg.cols/16);
            int y(mainImg.rows - logoImg.rows + mainImg.rows/16);

            cv::Mat imgROI(mainImg(cv::Rect(y, x, logoImg.cols, logoImg.rows)));
            cv::addWeighted(imgROI,1.f,logoImg,scale,0.f,imgROI);

            cv::namedWindow("Main Window");
            cv::imshow("Main Window", mainImg);
            cv::waitKey(7500);
        }
        else
            std::cout<<"Could not load logo image";
    }
    else
        std::cout<<"Could not load image";
    std::cin.ignore();
    std::cin.get();

    return 0;
}

logo image dimensions: 145x48 3-channel main image dimesnions: 1280x800 3-channel

edit retag flag offensive close merge delete

Comments

1

which exception do you get, exactly ?

(also, both images have to be same size for addWeighted())

berak gravatar imageberak ( 2016-01-21 23:43:33 -0500 )edit

Both images passed to AddWeighted are of the same sizes. The exception is an instance of cv::Exception. It wasn't clear to me what exception in particular was thrown. Take a look: http://i1380.photobucket.com/albums/a...

the.Aceix gravatar imagethe.Aceix ( 2016-01-22 10:09:28 -0500 )edit

This is happening in the line above, when you initialize imgROI. You're going out of bounds on mainImg.

Tetragramm gravatar imageTetragramm ( 2016-01-22 17:11:06 -0500 )edit

I don't see how I'm going out of bounds.

the.Aceix gravatar imagethe.Aceix ( 2016-01-28 09:53:12 -0500 )edit

I don't know the exact numbers you're using, but the exception says that you are. The exception comes from the ROI function, not the addWeighted.

Either y < 0, y+logoImg.cols > mainImg.cols or x<0, x+logoImg.rows > mainImg.rows

Note that you have y on the width and x on the height, which is backwards from convention. That could be the source of your problem.

Tetragramm gravatar imageTetragramm ( 2016-01-28 16:29:15 -0500 )edit