I have a small issue that I can't solve. I have looked every other related questions for 2 days. I searched opencv documentation and did several small tests, but I couldn't achieve. Here is my problem:
I have a float array. Let's assume that pointer to the first element is ptr. I want to create cv::Mat out of this pointer with some dimension like below:
auto mat = cv::Mat(1, m, CV_32F, ptr)
The matter is that, as array is float each element takes 4 bytes. So, during constructing cv::Mat, it will take elements sequentially from array buy adding 1 to the ptr. However, what if I want to sample and take every 3'rd element. I couldn't achieve this.
For more clarity let me give this example:
float[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
auto ptr = arr
auto mat = cv::Mat(1, 3, CV_32F, ptr)
std::cout << mat << "\n" // this should print [1, 4, 7, 10]
So, how should I change the code to achieve that? I know that I can set step parameter in cv::Mat constructor, but it doesn't give the same result.
Thank you for your time and attention.
I don't know the full extent of your problem. You might have further constraints that invalidate my answer, but it's valid for what you present so far.
One possible solution could be to consider rows of length 1, because you can have padding between rows, via step
argument.
I'm taking your question's pseudo-code (missing semicolons, float[]
is not known to me to be C++ syntax) and present pseudo-code in turn.
Docs for that Mat() constructor
float[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
cv::Mat mat(3, 1, CV_32F, arr, 12) // 3 rows, 1 element per row, 12 bytes per row
You could also make a cv::Mat
over the entire source array, having several 3-length rows, then use cv::Mat::col()
to select the first column.
Either of the above will give you column-shaped matrix. If you wanted a row-shaped matrix instead, you would need to reshape
.
However, the obtained column matrix is not considered continuous.
Due to that, you can't just reshape
that matrix. You'll have to make a copy (with clone()
) first, which will be continuous.
Then you can reshape
that matrix into a single-row matrix.
mat = mat.clone().reshape(1, 1) // cn, rows