在另一个分配的矩阵中为特定范围创建 cv::Mat 标头
create cv::Mat header for a certain range within another allocated matrix
我希望给定的 ColumnVector 的值被右移并复制到另一个比 ColumnVector 大 1 elemnt 的 RowVector。我想通过将columnVector复制到RowVector中的某个范围来实现这一点。
// The given columnVector ( this code snippet is added to make the error reproducable)
int yDimLen = 26; // arbitrary value
cv::Mat columnVector(yDimLen, 1, CV_32SC1, cv::Scalar(13)); // one column AND yDimLen rows
for (int r = 0; r < yDimLen; r++) // chech the values
{
printf("%dt", *(columnVector.ptr<int>(r)));
}
// Copy elemnets of columnVector to rowVector starting from column number 1
cv::Mat rowVector(1, yDimLen + 1, CV_32SC1, cv::Scalar(0));
cv::Mat rowVector_rangeHeader = rowVector.colRange(cv::Range(1, yDimLen + 1)); // header matrix, 1 in included AND (yDimLen + 1) is excluded
columnVector.copyTo(rowVector_rangeHeader);
// check the values
printf("n---------------------------------n");
for (int c = 0; c < yDimLen; c++)
{
printf("%dt", rowVector_rangeHeader.ptr<int>(0)[c]); // displays 13
}
printf("n---------------------------------n");
for (int c = 0; c < yDimLen + 1; c++)
{
printf("%dt", rowVector.ptr<int>(0)[c]); // displays 0 !!!
}
标头矩阵是否不指向包含rowVector的相同内存地址? 如果没有,如何将数据复制到行的某个部分?
来自cv::Mat::copyTo
的文档:
在复制数据之前,该方法调用:
m.create(this->size(), this->type());
以便在需要时重新分配目标矩阵。
每当目标的形状或数据类型与源不匹配时,都需要重新分配。在你的例子中,它是形状。为了演示这一点,让我们围绕copyTo
调用添加一些跟踪:
std::cout << "Shapes involved in `copyTo`:n";
std::cout << "Source: " << columnVector.size() << "n";
std::cout << "Destination: " << rowVector_rangeHeader.size() << "n";
columnVector.copyTo(rowVector_rangeHeader);
std::cout << "After the `copyTo`:n";
std::cout << "Destination: " << rowVector_rangeHeader.size() << "n";
输出:
Shapes involved in `copyTo`:
Source: [1 x 26]
Destination: [26 x 1]
After the `copyTo`:
Destination: [1 x 26]
解决方案很简单 - reshape
源以匹配目标。
columnVector.reshape(1, 1).copyTo(rowVector_rangeHeader);
现在我们得到以下输出:
Shapes involved in `copyTo`:
Source: [1 x 26]
Destination: [26 x 1]
After the `copyTo`:
Destination: [26 x 1]
rowVector
内容如下:
[0, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13]
作为替代方案,您可以将std::copy
与MatIterator
一起使用。
std::copy(columnVector.begin<int>()
, columnVector.end<int>()
, rowVector_rangeHeader.begin<int>());
rowVector
内容与以前相同:
[0, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13]
相关文章:
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 在函数内创建的对象的范围 - 如果在函数外部存储和访问引用,它们是否有效?
- 创建包装升压适配器的自定义范围类
- std::线程不是全局变量,但在到达创建它的函数的末尾时不会超出范围?
- 创建结构体向量,表达式:向量下标超出范围
- 如何在提升日期时间中创建日期范围?
- 如果一个对象是在本地创建的,并在C++中作为异常抛出,那么本地对象如何在其范围之外有效,即在 catch 块中?
- 在另一个分配的矩阵中为特定范围创建 cv::Mat 标头
- 如何根据范围创建名称
- 如何创建一个类似"范围"的浮点数可迭代对象?
- 如何创建一个结构的实例,当它不在范围内时,该实例将不会被删除
- 如何使用范围 v3 创建view_facade
- 创建大小为其他两个矩阵大小的矩阵时超出范围
- 按值函数创建范围的临时对象
- 提升精神范围字符规则创建空字符
- 创建二次公式求解器-范围中未声明的变量
- 如何全局创建对象并使用该对象访问全局范围内的公共成员函数
- 如何使用带有范围的 c++ 创建 XLL 文件
- 如何根据过滤的数据创建笛卡尔产品范围
- 从矢量范围创建矢量时的堆芯转储