OpenCv 图像块,大小错误

OpenCv image blocks, size error?

本文关键字:错误 图像 OpenCv      更新时间:2023-10-16

我有一个函数,可以使用C++和OpenCv将图像拆分为块以进行进一步处理。

这是我的代码:

  void imageSplit(Mat image)
    {
        int blockNumber = 8;
        // get the image data
        int height = image.rows;
        int width = image.cols;

        //set how many blocks and create vector to store
        cv::Size smallSize(height / blockNumber, width / blockNumber);
        std::vector < Mat > smallImages;
        for (int y = 0; y < image.rows; y += smallSize.height)
        {
            for (int x = 0; x < image.cols; x += smallSize.width)
            {
                cv::Rect rect = cv::Rect(x, y, smallSize.width, smallSize.height);
                //cout << x << " " << y << " " << smallSize.width << " " << smallSize.height << endl;
                smallImages.push_back(cv::Mat(image, rect));
            }
        }
    }

它适用于更大的区域(512 x 512 有效)但是当我降低到 100 x 100 像素这样的尺寸时,它给了我:

OpenCV Error: Assertion failed (0 <= roi.x && 0 <= roi.width && roi.x + roi.widt
h <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows) in
 cv::Mat::Mat, file srcmatrix.cpp, line 323
default exception.

问题是否与尺寸有关?如果是这样,有没有办法解决它?

因为 berak 因没有实际提交问题的答案而臭名昭著。

您的代码需要:

    for (int y = 0; y < image.rows-smallSize.height; y += smallSize.height)
    {
        for (int x = 0; x < image.cols-smallSize.width; x += smallSize.width)
        {
            cv::Rect rect = cv::Rect(x, y, smallSize.width, smallSize.height);
            //cout << x << " " << y << " " << smallSize.width << " " << smallSize.height << endl;
            smallImages.push_back(cv::Mat(image, rect));
        }
    }
}

这是为了阻止您递增到实际上没有图像的区域。