c++ - 更改现有的 cv::Mat 尺寸,同时保留适合新尺寸的内容
问题描述
我有一组不同大小的 cv::Mat 对象。我希望它们都具有与集合中最宽的矩阵相同的列数。列较少的矩阵应使用固定颜色填充到右侧。本质上,我想要与 Photoshop 的“Canvas Size...”操作相同的功能。我应该如何在 C++ 中做到这一点?
cv::resize不会剪切它,因为它会拉伸内容,而不是填充它。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;
}
推荐阅读
- flutter - Flutter - 文本值在 ontap 后未更新
- docker - 如何将 docker inspect 的结果设置为 gitlab-ci 脚本中的环境变量
- python - AttributeError:模块“matplotlib”没有属性“imread”
- c++ - 为什么这会给出运行时错误?我想我也在用循环写
- mysql - 为什么 cast,convert 在以下情况下不能在圆形,地板工作的地方工作
- command-line-interface - Microsoft App Center - 使用 appcenter-cli 分配团队
- conv-neural-network - Dnnl 一个 API - 非零填充
- html - 长页面底部的模态打开,而不是顶部
- mysql - 基于会话变量的 MySQL 中 If/else 条件的正确使用
- python - 使用 Stack 基于数字评估 Postfix 表达式