代码之家  ›  专栏  ›  技术社区  ›  Grillteller

OpenCV错误:cv::Mat第522行中的断言失败

  •  0
  • Grillteller  · 技术社区  · 7 年前

    调试时没有出现错误,但当我尝试执行该函数时,出现以下错误:

    OpenCV错误:在cv::Mat::Mat文件C:\OpenCV\OpenCV master\modules\core\src\matrix中,断言失败(0<=roi.x&0<=roi.width&roi.x+roi.width<=m.cols&0<=roi.y&0<=roi.height&roi.y+roi.height<=m.rows)。cpp,第522行

    这是我的代码:

    void divideImage(Mat input_image, vector<Mat> output_images, int width_fraction, int height_fraction ) {
    
    int width = input_image.rows / width_fraction - 1;
    int height = input_image.cols / height_fraction - 1;
    
        for (int w = 0; w < input_image.rows; w+=width) {
            for (int h = 0; h < input_image.cols; h+=height) {
                Mat tiles = input_image(Rect(w, h, width, height));
                output_images.push_back(tiles);
            }
        }
    }
    
    
    
    int main(int argc, char** argv)
    {
    
    // Get parameters from command line
    CommandLineParser parser(argc, argv, keys);
    String image_path1 = parser.get<String>(0);
    
        if (image_path1.empty())
        {
            help();
            return -1;
        }
    
    // Load image 
    cv::Mat img_1_rgb = imread(image_path1, 1);
    Mat img_1;
    cvtColor(img_1_rgb, img_1, CV_BGR2GRAY);
    
    vector<Mat> output_images(4);
    
    divideImage(img_1, output_images, 2, 2);
    

    我的投资回报率似乎有些出界。

     void divideImage(Mat input_image, vector<Mat> output_images, int width_fraction, int height_fraction ) {
    
     int width = (input_image.cols / width_fraction) - 1;
     int height = (input_image.rows / height_fraction) - 1;
    
    for (int w = 0; w < input_image.cols-width_fraction*width_fraction; w+=width) {
        for (int h = 0; h < input_image.rows-height_fraction*height_fraction; h+=height) {
            Mat tiles = input_image(Rect(w, h, width, height));
            output_images.push_back(tiles);
            //cout << w << " " << h << " " << width << " " << height << " " << endl;
        }
    }
    

    }

    1 回复  |  直到 7 年前
        1
  •  1
  •   api55    7 年前

    假设您的图像大小为640x480

    现在,让我们用您使用的相同参数计算函数的宽度变量

    int width = 640 / 2 - 1; // 319
    

    w=0 你会得到这样的结果

    Rect(0, 0, 319, 239)
    

    然后对于下一个宽度迭代,您将有 w+=width 这就是 w=319

    Rect(319, 0, 319, 239)
    

    第二次迭代将具有 w+=宽度 再说一次 w=638 ,正如您清楚地看到的那样,638比我的图像(640)中的行少,因此它将尝试这样做

    Rect(638, 0, 319, 239)
    

    投资回报率x+投资回报率。宽度<=m、 科尔斯

    将被翻译为

    638 + 319 <= 640
    

    这是错误的。

    您必须改变它的循环方式,同样在它工作的最佳情况下,您将失去n列/行,即n个分区数。(您可以尝试设置一个限制,如

    input_image.rows - width_fraction
    

    进一步建议,学习如何使用调试器!!它应该跳转到断言上,除非您在发布模式下运行它,否则,如果出现问题,代码应该始终失败。