Stride on image using Opencv C++

Seltymar picture Seltymar · Jul 20, 2012 · Viewed 7.9k times · Source

I am on windows and use opencv 2.4.2 on C++. I read an image with imread and put it in a Mat object. After that, i get a pointer on the raw data using the function ptr of the Mat class. I would like to know how works imread when the image contains stride. Is there stride in the data of the Mat or only data of pixels ?

Additional information: I need the raw data because I am using a code written with array and I don't want to change it for the Mat class.

Answer

Martin Beckett picture Martin Beckett · Jul 20, 2012

The stride is that each new row of pixels in the cv::Mat doesn't start after the end of the last row. This is because the memory is faster if it starts on a multiple of 4bytes - so it only matters if the number of bytes in a row (number of pixels * number of colours) isn't a multiple of 4.

You can check .isContinuous() will return true if there is no stride

The safest way of accessing an image is to loop over all the rows and use .ptr(row) to get a pointer to the start of the row, then do any processing on that row.

If you need to mix opencv with other libs you can create a cv::mat that will use your own memory for the data and you can tell opencv that there is no stride on this

For lots of details see https://docs.opencv.org/2.4/modules/core/doc/basic_structures.html