使用简单模式创建OpenCV Mat

时间:2015-08-10 05:49:23

标签: java c++ opencv

在OpenCV中,有一种快速创建Mat对象的方法,其中:

  • 奇数列是' 1'
  • 偶数列是' 0'

例如:

1 0 1 0 1 0
1 0 1 0 1 0
1 0 1 0 1 0

模式总是一样的。 Mat的大小可能很大,通过循环处理生成此模式的速度非常慢。

3 个答案:

答案 0 :(得分:10)

OpenCV repeat就是这样的。

#include <opencv2\opencv.hpp>
#include <vector>

using namespace std;
using namespace cv;

int main(int argc, char** argv)
{
    int rows = 1000;
    int cols = 1000;

    vector<uchar> pattern = { 1, 0 }; // change with int, double, etc according to the type you want.
    Mat m;
    repeat(pattern, rows, cols/2, m);

    return 0;
}

与其他方法的比较

测量拟议(迄今为止)方法的性能只是一个小测试:

以毫秒为单位的时间:

@Miki [repeat]          : 0.442786
@RonaldoMessi [copyTo]  : 7.26822
@Derman [merge]         : 1.17588

我用于测试的代码:

#include <opencv2\opencv.hpp>
#include <vector>
#include <iostream>

using namespace std;
using namespace cv;

int main(int argc, char** argv)
{
    int rows = 1000;
    int cols = 1000;

    {
        // @Miki
        double tic = (double)getTickCount();

        vector<uchar> pattern = { 1, 0 };
        Mat m1;
        repeat(pattern, rows, cols / 2, m1);

        double toc = ((double)getTickCount() - tic) * 1000 / getTickFrequency();
        cout << "@Miki [repeat] \t\t: " << toc << endl;
    }

    {
        // @RonaldoMessi
        double tic = (double)getTickCount();

        Mat m2(rows, cols, CV_8UC1);
        Mat vZeros = Mat::zeros(rows, 1, CV_8UC1);
        Mat vOnes = Mat::ones(rows, 1, CV_8UC1);

        for (int i = 0; i < cols - 1; i += 2)
        {
            vOnes.col(0).copyTo(m2.col(i));
            vZeros.col(0).copyTo(m2.col(i + 1));
        }

        double toc = ((double)getTickCount() - tic) * 1000 / getTickFrequency();
        cout << "@RonaldoMessi [copyTo] \t: " << toc << endl;
    }

    {
        // @Derman
        // NOTE: corrected to give correct output

        double tic = (double)getTickCount();

        Mat myMat[2];
        myMat[0] = cv::Mat::ones(rows, cols/2, CV_8UC1);
        myMat[1] = cv::Mat::zeros(rows, cols/2, CV_8UC1);

        Mat m3;
        merge(myMat, 2, m3);
        m3 = m3.reshape(1);

        double toc = ((double)getTickCount() - tic) * 1000 / getTickFrequency();
        cout << "@Derman [merge] \t: " << toc << endl;
    }

    getchar();

    return 0;
}

答案 1 :(得分:1)

您可以创建两个列向量 vZeros vOnes ,然后将这些列复制到矩阵M:

jsonObject.abc.as = 1
jsonObject.abc.asa = 2
jsonObject.abc.sd = 3

答案 2 :(得分:1)

如果双通道矩阵不会打扰你,这可能是你的选择:

int rows = 5;
int cols = 5;

cv::Mat myMat[2];
myMat[0] = cv::Mat::ones(rows, cols, CV_32FC1);
myMat[1] = cv::Mat::zeros(rows, cols, CV_32FC1);

cv::Mat result;
cv::merge(myMat, 2, result);

这是你的结果:

[1, 0, 1, 0, 1, 0, 1, 0, 1, 0;
1, 0, 1, 0, 1, 0, 1, 0, 1, 0;
1, 0, 1, 0, 1, 0, 1, 0, 1, 0;
1, 0, 1, 0, 1, 0, 1, 0, 1, 0;
1, 0, 1, 0, 1, 0, 1, 0, 1, 0]