我有一组不同大小的 cv::Mat 对象。我希望它们都具有与集合中最宽矩阵相同的列数。列较少的矩阵应该用固定颜色填充到右边。本质上,我想要与 Photoshop 的“Canvas Size...”操作相同的功能。我应该如何在 C++ 中执行此操作?
cv::resize不会剪切它,因为它会拉伸(stretch)内容,而不是填充它。 cv::Mat::resize也不符合要求,因为它只能添加行,不能添加列。
最佳答案
诀窍是创建一个具有所需尺寸的新矩阵,然后将数据从原始图像复制到代表保留数据的 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;
}
关于c++ - 更改现有 cv::Mat 尺寸,同时保留适合新尺寸的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53502957/