Change channels order (Python's permute equivalent)?


I need to classify in C++ a BMP image within 20ms.
Once the file opened, I have a pointer to an array, where the RGB pixels are stored one after the other.
So I need to fill a Tensor as fast as possible from this array. Here is the code I use:

torch::Tensor image = torch::zeros({window_height, window_width, 3});
auto p = image.accessor<float, 3>();
for (int yy = origin_y; yy < origin_y + window_height; yy++) {
	// unsigned char *addr_line = addr_origin + yy * width * step;
	unsigned char *addr_line = addr_origin + (height - 1 - yy) * width * step;

	for (int xx = origin_x; xx < origin_x + window_width; xx++) {
		// 1 - Image coded in BGR, but Tensors are RGB
		// 2 - BMP images are coded from bottom to top. Pixel (i, j) once flipped is then (height - 1 - i, j)
		auto tensor_pixel = p[yy - origin_y][xx - origin_x];
		auto array_pixel = addr_line + xx * step;
		tensor_pixel[0] = *(array_pixel + 2) / 255.;
		tensor_pixel[1] = *(array_pixel + 1) / 255.;
		tensor_pixel[2] = *(array_pixel) / 255.;
image = torch::unsqueeze(image, 0);

I put the channel dimension in 3rd position to speed up the filling, but how can I put it back in first position before unsqueezing (for the batch dimension)? I’m looking for a function similar to “permute” in Python


permute is also available in the C++ backend via:

image.permute({2, 0, 1}); 

Awesome, thanks a lot!
Would you have any tip to have a better understanding of the documentation? I’m having a hard time using the C++ backend of Libtorch, there aren’t that many examples of use (at least, not easily findable…).


I’m checking the C++ docs first for a matching function (for permute I knew it was there) and if I cannot find it, I’m usually checking the C++ code (the libtorch tests are a good place to see examples) for the method.

Alright, will try to remember that before asking obvious questions. Thanks :slight_smile:

Sure, but also feel free to post here in case you cannot find anything and think the documentation doesn’t mention the method. :wink:

1 Like