将cv :: Mat复制到另一个创建"断言失败0< = _colRange.start&& .."

时间:2016-08-07 07:59:07

标签: c++ opencv

一个非常简单的概念,我有640x480 Mat和800x480屏幕,所以我试图将原始图像复制到黑色800x480图像的中心,以便保持纵横比但是使用整个屏幕。

我跟踪this帖子并尝试了两种解决方案(直接复制到感兴趣的区域)并得到同样的错误:

OpenCV Error: Assertion failed (0 <= _colRange.start && _colRange.start <= _colRange.end && _colRange.end <= m.cols) in Mat, file /home/pi/opencv-3.0.0/modules/core/src/matrix.cpp, line 464
terminate called after throwing an instance of 'cv::Exception'
  what():  /home/pi/opencv-3.0.0/modules/core/src/matrix.cpp:464: error: (-215) 0 <= _colRange.start && _colRange.start <= _colRange.end && _colRange.end <= m.cols in function Mat

Aborted

违规代码:

cv::Mat displayimage = cv::Mat(800, 480, CV_16U, cv::Scalar(0));
modimage1.copyTo(displayimage.rowRange(1,480).colRange(81,720));

我首先用(0,480)和(80,720)的开始/结束范围/行尝试它,但是然后错误使它听起来不能从0开始,所以当然我认为我已经关闭了由1开始,我从1开始,结果相同。但实际上,错误是针对COLUMNS而不是ROWS,并且列偏离1并不重要。那么我试图将这张图片复制到哪里并不是什么感觉?

2 个答案:

答案 0 :(得分:2)

Duh,这个比我想象的容易。 cv :: Mat()参数是高度THEN宽度,而不是宽度然后高度。棘手。但是我的垫子类型的通道数量也出现了错误,因此为了使代码具有防弹性,我只是将其初始化为与复制到它的图像相同的图像类型,因此下面的代码工作正常:

cv::Mat displayimage = cv::Mat(480, 800, modimage1.type(), cv::Scalar(0));
modimage1.copyTo(displayimage.rowRange(0,480).colRange(80,720));

答案 1 :(得分:1)

您可以使用cv::copyMakeBorder

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

using namespace cv;
using namespace std;

int main(int argc, char* argv[])
{
    Mat src = imread(argv[1]);
    if (src.empty())
    {
        cout << endl
             << "ERROR! Unable to read the image" << endl
             << "Press a key to terminate";
        cin.get();
        return 0;
    }

    imshow("Source image", src);

    Mat dst;

    Size dst_dims = Size(800,480);
    int top = ( dst_dims.height - src.rows ) / 2;
    int bottom = ( (dst_dims.height + 1) - src.rows ) / 2;
    int left = ( dst_dims.width - src.cols ) / 2;
    int right = ( ( dst_dims.width + 1 ) - src.cols ) / 2;

    copyMakeBorder(src, dst, top, bottom, left, right, BORDER_CONSTANT, Scalar(0,0,0));

    imshow("New image", dst);
    waitKey();

    return 0;
}