将 cv::Mat 复制到另一个会创建"assertion failed 0 <= _colRange.start && .."

Copying cv::Mat to another creates "assertion failed 0 <= _colRange.start && .."

本文关键字:lt cv start colRange failed 另一个 复制 创建 assertion Mat      更新时间:2023-10-16

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

我关注了这篇文章,尝试了两种解决方案(直接复制到和感兴趣的区域(,得到了相同的错误:

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));

我第一次尝试的是(0480(和(80720(的开始/结束范围/行,但后来错误让它听起来像是无法在0开始,所以我当然认为我落后了1,我在1开始时也得到了同样的结果。但事实上,错误是针对列而不是ROWS的,并且列被关闭1也无关紧要。那么,我试图将此图像复制到的位置有什么不喜欢的地方呢?

Duh,这个比我想象的要容易。cv::Mat((参数是height THEN width,而不是width THEN height。棘手的但我也遇到了一个错误,我的垫子类型的通道数量不对,所以为了使代码防弹,我只是将其初始化为将复制到它的图像的相同图像类型,所以下面的代码运行良好:

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

您可以使用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;
}