OpenCV:连续矩阵和非连续矩阵之间的真正性能差异是什么?

pet*_*ent 1 opencv matrix

目前我正试图了解openCV中连续矩阵和非连续矩阵之间的一些差异.有人告诉我,连续矩阵提供了更好的性能,因为程序不必跳回到每列末尾的下一行的开头.

总之,连续和非连续矩阵之间的可比性能差异是什么?

Ser*_*sov 5

嗯,这主要取决于你如何使用你的矩阵.如果你正在进行大量的"跳跃" - 它不会有太大的区别,但在"连续"使用情况下,它会影响几十个百分点.

下面的例子(简单地移动矩阵值)给出了一个输出:

image.isContinuous() = 1
roi.isContinuous() = 0
image: 0.0162504 s
roi: 0.0219723 s
Sanity check: OK
Run Code Online (Sandbox Code Playgroud)

这差别约为30%.您的millage将根据硬件和实际用例而有所不同.

来源(注意在这种情况下第一个循环如何更简单):

#include <opencv2/core/core.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main( int argc, char** argv )
{
    int cols = 4096;
    int rows = 4096;
    int scale = 2;

    Mat image(rows, cols, CV_8UC1);
    Mat image_big(rows * scale, cols * scale, CV_8UC1);
    Mat roi = image_big(Rect(0, 0, cols, rows));

    randu(image, 0, 255);
    image.copyTo(roi);

    cout << "image.isContinuous() = " << image.isContinuous() << "\n" << "roi.isContinuous() = " << roi.isContinuous() << endl;

    {
        cout << "image: ";
        double start = getTickCount();
        for (int i = 1; i < image.total(); i++)
        {
            image.data[i - 1] = image.data[i];
        }
        cout << (getTickCount() - start)/getTickFrequency() << " s" << endl;
    }

    {
        cout << "roi: ";
        double start = getTickCount();
        for (int y = 0; y < roi.cols; y++)
        {
            if (y != 0) {
                roi.ptr<char>(y-1)[roi.cols-1] = roi.ptr<char>(y)[0];
            }

            for (int x = 1; x < roi.rows; x++)
            {
                roi.ptr<char>(y)[x - 1] = roi.ptr<char>(y)[x];
            }
        }
        cout << (getTickCount() - start)/getTickFrequency() << " s" << endl;
    }

    cout << "Sanity check: " << (countNonZero(image - roi) ? "FAIL" : "OK") << endl;
}
Run Code Online (Sandbox Code Playgroud)