1. 程式人生 > >Opencv學習問題(一)-------- neither 'array op array' nor 'array op scalar'

Opencv學習問題(一)-------- neither 'array op array' nor 'array op scalar'

今天照著例程學習了一下,但是自己編的時候出現了出錯誤。

程式碼如下:

#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;

int main(int argc, char *argv[])
{
    Mat sourceImage;
    Mat imageROI,imageROI1,imageROI2;
    Mat logo=imread("dota_logo.jpg");

    imshow("the logo",logo);
    vector<Mat> channels;
    sourceImage=imread("1.jpg");
    //  imshow("the source",sourceImage);
    split(sourceImage,channels);
    imageROI=channels.at(0);
    imshow("ROI",imageROI);
    imageROI1=channels.at(1);
    imshow("ROI1",imageROI1);
    addWeighted(imageROI(Rect(15,20,logo.cols,logo.rows)),1.0,logo,0.5,0,
                imageROI(Rect(15,20,logo.cols,logo.rows)));

    merge(channels,sourceImage);
    imshow("the picture",sourceImage);
    waitKey(0);
    return 0;
}

經過一步步註釋(沒辦法,人太笨),發現是主要的新增函式有問題:

 addWeighted(imageROI(Rect(15,20,logo.cols,logo.rows)),1.0,logo,0.5,0,
                imageROI(Rect(15,20,logo.cols,logo.rows)));

其中logo是我想要疊加的圖片,imageROI是單通道的圖片。

得到如下錯誤:

OpenCV Error: 
Sizes of input arguments do not match (The operation 

is neither 'array op array' (where arrays have the same size and the same number of channels), 

nor 'array op scalar', nor 'scalar op array')

搞了很久不知道原因,在網上查了一下,瞬間滴汗,原來是圖片格式不對。

因為在上面的程式碼裡面,我的imageROI是單通道的影象,而logo是jpg格式的,三通道,所以二者的格式大小必須一樣。

修改如下:

 Mat logo=imread("dota_logo.jpg");

//將logo也變為灰度圖

 Mat logoGray=Mat(logo.rows,logo.cols,CV_8UC1);
    
cvtColor(logo,logoGray,CV_BGR2GRAY);

//修改addWeighted,將logo變為logoGray

addWeighted(imageROI(Rect(15,20,logo.cols,logo.rows)),1.0,

                logoGray,0.5,0,

                imageROI(Rect(15,20,logo.cols,logo.rows)));

執行一看,不錯!