Opencv:如何从现有矩阵创建新矩阵有一些变化? [英] Opencv: how to create new matrix from existing matrix with some changes?
问题描述
在OpenCV中,我有这样的矩阵:[3 4 2; 5 2 1; 6 7 9],即3x3大小。现在我想把它改为3x1大小,并像这样:
[3 4 2 5 2 1 6 7 9]。但这不是我想要的,我的实际目标是在每个值之前和之后放置零,同时重复每个值三次。所以我的目标矩阵应该是这样:[0 3 3 3 0 0 4 4 4 0 0 2 2 2 0 0 5 5 5 0 0 2 2 2 0 0 1 1 1 0 0 6 6 6 0 0 7 7 7 0 0 9 9 9 0]。我为此写了以下代码:
in OpenCV, I have a matrix like this: [3 4 2; 5 2 1; 6 7 9], that is with 3x3 size. Now I want to change it into 3x1 size, and be like this: [3 4 2 5 2 1 6 7 9]. But this is not exactly what I want, my actual goal is to put zero before and after each value, at the same time repeat each value three times. So my goal matrix should be like this: [ 0 3 3 3 0 0 4 4 4 0 0 2 2 2 0 0 5 5 5 0 0 2 2 2 0 0 1 1 1 0 0 6 6 6 0 0 7 7 7 0 0 9 9 9 0 ]. I wrote the following code for this:
for ( int i = 0; i < 3; i ++ )
{
for ( int j = 0; j < 3; j ++ )
{
for ( int m = k + 1; m < m + 3; m ++ )
{
dstMat.col (m) = srcMat.at <int> ( i, j );
}
k = k + 5 ;
}
}
有更好的方法吗?特别是没有for循环,这是真的时间混乱。提前谢谢了。
Is there any better way for doing is? Especially without "for" loop, it is really time confusing. Many thanks in advance.
推荐答案
您可以使用 Mat :: reshape 将3x3矩阵转换为3x1。这样,你需要一个for循环,而不是两个,它是一个 O(1)
操作。
You can use Mat::reshape to convert your 3x3 matrix to 3x1. This way you'll need one for loop instead of two, and it's an O(1)
operation.
你可以通过使用ROI来省略下一个for循环:
you can omit the next for loop by using ROI:
srcMat.reshape(0,1);
for (int i =0; i < 9; i++)
dstMat(cv::Range::all(), cv::Range(i*5+1, i*5+4)).setTo(srcMat.at<int>(i));
这将是全部。
这篇关于Opencv:如何从现有矩阵创建新矩阵有一些变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!