下面是您修复的代码,以便将图像分解为 nxn 个图块。
首先你计算的unitWidth
andunitHeight
不正确,这就是断言失败的原因。它应该是:
int unitWidth = image.cols / n; // you had image.rows / n;
int unitHeight = image.rows / n; // " " image.cols / n;
此外,如果你想要一个 nxn 平铺,你需要循环 n^2 次,而不仅仅是 n 次。最简单的方法是只有两个循环,一个在另一个内部,一个循环 n 次用于行,另一个循环 n 次用于列。
for(int i = 0; i < n; i++) { //i is row index
// inner loop added so that more than one row of tiles written
for(int j = 0; j < n; j++) { // j is col index
//Take the next tile in the nxn grid. Unit is the width and height of
//each tile. i%n and i/n are just fancy ways of a double x,y for loop
// Mat subImage = image(Rect((i % n) * unitWidth, (i / n) * unitHeight, unitWidth, unitHeight));
// I didn't understand the above line, as ((i % n)==i and (i / n)==0.
//
Mat subImage = image(Rect(j * unitWidth, i * unitHeight, unitWidth, unitHeight));
ostringstream oss;
oss << i << "_" << j << ".jpg";
string name = oss.str();
imwrite(name, subImage);
}
}
调试这样的代码的最简单方法是使 Rect 成为一个单独的对象,以便您可以打印出它的 x、y、width、height 并根据 OpenCV 断言消息检查它们。你有没有在调试模式下编译你的代码?
cv::Rect roi(j * unitWidth, i * unitHeight, unitWidth, unitHeight);
cout << "(i, j) = (" << i << ", " << j << ")" << endl;
cout << "(i %n) = " << i%n << endl;
cout << "(i/n) = " << i/n << endl;
cout << "roi.x = " << roi.x << endl;
cout << "roi.y = " << roi.y << endl;
cout << "roi.width = " << roi.width << endl;
cout << "roi.height = " << roi.height << endl;
Mat subImage = image(roi);