首页 > 解决方案 > 更改现有的 cv::Mat 尺寸,同时保留适合新尺寸的内容

问题描述

我有一组不同大小的 cv::Mat 对象。我希望它们都具有与集合中最宽的矩阵相同的列数。列较少的矩阵应使用固定颜色填充到右侧。本质上,我想要与 Photoshop 的“Canvas Size...”操作相同的功能。我应该如何在 C++ 中做到这一点?

cv::resize不会剪切它,因为它会拉伸内容,而不是填充它。cv::Mat::resize也不符合要求,因为它只能添加行,但不能添加列。

标签: c++opencv

解决方案


诀窍是创建一个具有所需尺寸的新矩阵,然后将原始图像中的数据复制到表示保留数据的 ROI 中:

// Creates a new matrix with size newSize with data copied from source.
// Source data outside the new size is discarded.
// If any of the dimensions of newSize is larger than that dimension in source,
// the extra area is filled with emptyColor.
cv::Mat resizeCanvas(const cv::Mat& source, cv::Size newSize, cv::Scalar emptyColor) {
    cv::Mat result(newSize, source.type(), emptyColor);

    int height = std::min(source.rows, newSize.height);
    int width = std::min(source.cols, newSize.width);
    cv::Rect roi(0, 0, width, height);

    auto sourceWindow = source(roi);
    auto targetWindow = result(roi);
    sourceWindow.copyTo(targetWindow);

    return result;
}

推荐阅读