Get 2D matrices from a 4 dimensional Mat, p.x. (1,256,256,3)


I am wondering how to get 2D matrices from a 4 dimensional Mat, p.x. (1,256,256,3)

For background according to net.forward cv::dnn results in a 4d Matrix.

[ For a net which gives NCHW as output (p.x. 1,3, 256,256) a working answer is mentionend in that forum post]

Using the onnx format, I get (1,256,256,3). Now different trys did not lead to success.

a) BruteForce using I found out, that rawOuput.Ptr(1,1,0) but also rawOutput.Ptr(1,1,1) results in one
of the three desired output. But I was not able access the other two layers.

b) One try was not to access every element of the 4d mat seperatly, but for I do not know how to handle that for a 4d Mat
I only found OpenCV: cv::Mat Class Reference
_Tp& cv::Mat::at(int i0, int i1, int i2)

Another idea was to reshape the the 4d mat to a vector with rawOutput.Reshape(1,1) and afterwards reshape
the vector to (256,256,3) [which should have the effect that the singelton dimension was removed, but I
was successful to create an fill a MAT the mentioned dimesions with the results of a the vector.
The MAT created should have the dimensions (256,256,3). After that I wanted to use how could I change memory layout from hwc to chw ? - OpenCV Q&A Forum
to change to the chw format. But I did not get a correct images.

I know the last ways look a bit cumbersome, but I thought maybe I’d get it running this way.

I would also be happy about hints/solutions of parts of my questions.

Thank you

to “squeeze” the batch dimension from the result, you can use a simple reshape:

Mat img = rawOutput.reshape(3,256); // 3 channels, 256 rows