c – 用零填充图像

我在C编码,我试图将图像2调整为与图像1相同的尺寸,但我不想拉伸图像.我试图将image2复制到填充矩阵(在点0,0).得到错误:

OpenCV Error: Assertion failed (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 Mat, file C:\opencv\opencv\modules\core\src\matrix.cpp, line 323

代码如下.提前致谢

    Mat padded;
    padded.setTo(cv::Scalar::all(0));
    padded.create(image1.rows,image1.cols, image2.type());
    image2.copyTo(padded(Rect(0, 0, image2.rows, image2.cols)));

最佳答案 您可以使用OpenCV功能
copyMakeBorder填充图像:

要实现您的目标,您可以尝试以下方法:

cv::Mat padded;

//Assuming that dimensions of image1 are larger than that of image2
//Calculate padding amount so that total size after padding is equal to image1's size
int rowPadding = image1.rows - image2.rows;
int colPadding = image1.cols - image2.cols;

cv::copyMakeBorder(image2, padded, 0, rowPadding, 0, colPadding, cv::BORDER_CONSTANT, cv::Scalar::all(0));
点赞