4

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

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
AkroB
  • 39
  • 4
  • Does this answer your question? [Difference between cv::Mat::t () and cv::transpose()](https://stackoverflow.com/questions/43310433/difference-between-cvmatt-and-cvtranspose) – YScharf Jun 01 '22 at 14:11
  • 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. – beaker Jun 01 '22 at 14:32
  • 3
    transpose((2,0,1)) converts from HWC to CHW channel order... – Christoph Rackwitz Jun 01 '22 at 15:18
  • 3
    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. – beaker Jun 01 '22 at 15:56

1 Answers1

10

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);
berak
  • 1,226
  • 2
  • 5
  • 7