OpenCV Mat array access, which way is the fastest for and why?

后端 未结 4 670
慢半拍i
慢半拍i 2021-01-13 05:39

I am wondering about the way of accessing data in Mat in OpenCV. As you know, we can access to get data in many ways. I want to store image (Width x Height x 1-depth) in Mat

4条回答
  •  迷失自我
    2021-01-13 06:32

    I realize this is an old question, but I think the current answers are somehow misleading.

    Calling both at(...) and ptr(...) will check the boundaries in the debug mode. If the _DEBUG macro is not defined, they will basically calculate y * width + x and give you either the pointer to the data or the data itself. So using at(...) in release mode is equivalent to calculating the pointer yourself, but safer because calculating the pointer is not just y * width + x if the matrix is just a sub-view of another matrix. In debug mode, you get the safety checks.

    I think the best way is to process the image row-by-row, getting the row pointer using ptr(y) and then using p[x]. This has the benefit that you don't have to count with various data layouts and still plain pointer for the inner loop.

    You can use plain pointers all the way, which would be most efficient because you avoid one the multiplication per row, but then you need to use step1(i) to advance the pointer. I think that using ptr(y) is a nice trade-off.

提交回复
热议问题