Ask Your Question

How to extract a 2D vector from 4D Mat and get maximum value

asked 2019-11-07 16:24:24 -0500

frengo gravatar image

updated 2019-11-07 16:26:39 -0500

Hi to all, I am playing a bit with dnn to improve my know how. I pass a camera frame through a network. Based on documentation at the official link


the output is a Mat with this shape

"shape: [1, 2, 1, 1] - Softmax output across 2 type classes".

So I would extract automatically the values at the indexes (0,0,0,0) and (0,1,0,0), store them in a vector<float> and get the maximum value between them. Is there a way to do it automatically in C++? Thank in advance Franco

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2019-11-08 01:28:00 -0500

berak gravatar image

updated 2019-11-08 01:51:36 -0500

your network reports age and gender at the same time, in different outputs:

vector<string> outnames = {"prob", "age_conv3"};
vector<Mat> outputs;
net.forward(outnames, outputs);
Mat prob = outputs[0];
Mat age_conv3 = outputs[1];

for the gender output (2 values), you can reshape() the 4d Mat into a 2d one, and then find the largest value, have a look at the classification example :

//! [Get a class with a highest score]
Point classIdPoint;
double confidence;
minMaxLoc(prob.reshape(1, 1), 0, &confidence, 0, &classIdPoint);
int classId = classIdPoint.x;

for the age output, there is only a single value:

float age = 100 * age_conv3.reshape(1, 1).at<float>(0,0);
edit flag offensive delete link more
Login/Signup to Answer

Question Tools

1 follower


Asked: 2019-11-07 16:24:24 -0500

Seen: 19 times

Last updated: Nov 08