How pass RGB image Mat to keras(ONNX) model with channels_last data format?

I couldn’t find any way to change channels place(3-channel) in Opencv Mat to pass it to ONNX model with channels_last dataformat. Please help me.

assuming, you got the image from imread(),
if your network input requires 3 channel input – leave it as-is.
if it needs 4, wrap another Mat header around the data, like:

img.convertTo(img, CV_32F, 1.0/255);

int sz[] = {1, img.rows, img.cols, img.channels()};
Mat blob(4, sz, CV_32F,;

just avoid the dnn::imageToBlob() function,
which will split the image planes to NCHW format !

1 Like

Thank you for your quick response, unfortunately, I am working with OpenCVForUnity, and there are no, but with your code I tried to use OpenCVForUnity Mat.Reshape with mentioned reshaped size. Project is working, I hope the dnn output will be expected after my tests. Thank you very much again!!!


1 Like