Different order of elements while std::cout print a cv::Mat than to iterate with cv::Mat begin(), end()

I have the following code to obtain a 32FC3 cv::Mat

cv::Mat imageBGR = cv::imread(imageFilepath, cv::ImreadModes::IMREAD_COLOR);
cv::Mat resizedImageBGR, resizedImageRGB, resizedImage, preprocessedImage;
cv::resize(imageBGR, resizedImageBGR,
cv::Size(inputDims.at(2), inputDims.at(1)),
cv::InterpolationFlags::INTER_CUBIC);
cv::cvtColor(resizedImageBGR, resizedImageRGB, cv::ColorConversionCodes::COLOR_BGR2RGB);
resizedImageRGB.convertTo(preprocessedImage, CV_32FC3);

Then if I print the preprocessedImage →

std::cout << preprocessedImage.cols * preprocessedImage.rows * preprocessedImage.channels() << "  " << preprocessedImage << std::endl;`

147456  [196, 211, 172, 217, 227, 189, 214, 224, 184, 216, 226, 187, 212, 222, 184 .....

Now I use that matrix to fill a vector of floats…

std::vector<float> inputTensorValues(inputTensorSize);

inputTensorValues.assign(preprocessedImage.begin<float>(),
 
preprocessedImage.end<float>());

And then I want to print the order of the vector…

std::cout << "Tensor = " << std::endl;

for (auto i: inputTensorValues) 
    std::cout << i << ' ';
 
std::cout << "End Tensor" << std::endl;

I obtain this order:

Tensor =
196 217 214 216 212 182 170 182 232 …


Which is different than the printed Mat.
So how can I obtain the order is printed by std::cout in the vector??
1 Like

different memory layout than Mat_<Vec3f> , your code copies only the 1st elem from each Vec3f (it’s NOT a matter of printing !)

std::vector<Vec3f> inputTensorValues(inputTensorSize);
inputTensorValues.assign(preprocessedImage.begin<Vec3f>(),
preprocessedImage.end<Vec3f>());

would work as expected

1 Like