C++ OpenCV transpose/permute image axes
Asked Answered
R

1

5

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++?

Resolution answered 1/6, 2022 at 12:48 Comment(4)
Does this answer your question? Difference between cv::Mat::t () and cv::transpose()Crippling
What are you actually trying to achieve in that line in Python? What is the context? Most of the conversions you have there are simply to change from the OpenCV shape/ordering to NumPy. You're not using NumPy in C++, so it doesn't make a lot of sense to change the image to a format NumPy likes.Sniffle
transpose((2,0,1)) converts from HWC to CHW channel order...Rockwell
Note that cv::transpose() will only transpose the first two dimensions, so it is not applicable if you really want to permute all 3 axes.Sniffle
S
15

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);
Stopover answered 1/6, 2022 at 16:1 Comment(1)
The img.ptr(N) parts in your code should be chw.ptr(N).Vanmeter

© 2022 - 2024 — McMap. All rights reserved.