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

OpenCV Error: Assertion failed in cv::Mat line 522

本文关键字:Mat 失败 cv 错误 断言 OpenCV      更新时间:2023-10-16

我正在尝试编写一个返回图像较小部分的函数。我正在使用函数 Rect(( 进行切割。 调试时没有收到错误,但是当我尝试执行该函数时,出现以下错误:

OpenCV 错误:断言失败(0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height &

& roi.y + roi.height <= m.rows( in cv::Mat::Mat,文件 C:\opencv\opencv-master\modules\core\src\matrix.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);

似乎我的投资回报率在某种程度上超出了界限。

在 api55 的帮助下,我提出了正确的循环:

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

}

你的代码是错误的。我举个例子:

假设您的图像大小为 640x480

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

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

现在让我们开始我们的循环,第一次w=0,你会得到类似的东西

Rect(0, 0, 319, 239)

然后对于下一个宽度迭代,您将w+=widthw=319和类似的东西

Rect(319, 0, 319, 239)

第二次迭代将再次具有w+=width,这是w=638,因为您可以清楚地看到 638 比我的图像的行 (640( 少,因此它将尝试这样做

Rect(638, 0, 319, 239)

这将跳过提到的断言,因为

投资回报率 + 投资回报率 宽度 <= m.cols

将被翻译成

638 + 319 <= 640

这是错误的。

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

input_image.rows - width_fraction

在 for 循环检查中,如果您不关心删除的列。

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