C++ OpenCV transpose/permute image axes

Viewed 426

I'm having a hard time to code this python line in C++:

Python:

frame_nn = cv2.cvtColor(padded, cv2.COLOR_BGR2RGB).transpose(2,0,1).astype(np.float32)[None,]

What I already got:

cv::cvtColor(image_pd, image_pd, cv::COLOR_BGR2RGB);
image_pd.convertTo(image_f, CV_32F);

How do I transpose a 3D maxtrix / image in C++? Basically what is the equivalent of image = numpy.transpose(image, (2, 0, 1)) in C++?

1 Answers

to convert from HWC to CHW channel order, you can use this (stolen from blobFromImage()):

int siz[] = {3, img.rows, img.cols};
Mat chw(3, siz, CV_8U);
vector<Mat> planes = {
    Mat(img.rows, img.cols, CV_8U, img.ptr(0)), // swap 0 and 2 and you can avoid the bgr->rgb conversion !
    Mat(img.rows, img.cols, CV_8U, img.ptr(1)),
    Mat(img.rows, img.cols, CV_8U, img.ptr(2))
};
split(img, planes);
chw.convertTo(chw, CV_32F);

[edit] from 4.6.0 on, you can also use transposeND()

Mat src=...
Mat dst;
transposeND(src, {2,0,1}, dst);
Related