1

How can I permute dimensions in cv::Mat from CxWxH to WxHxC (Width x Height x Channels)?

I.e. how can I convert Mat:

  • from cv::Mat frame (1000, 1000, CV_8UC3) = cv::imread("image.jpg", -1);

    with dimesions: channels, width, height

  • to Mat with dimesions: width, height, channels int sizes_inputs[] = { 3, 1000, 1000 }; cv::Mat out_image(3, sizes_inputs, CV_8UC);

Is there in OpenCV a ready-made fast function for such a conversion? Or should I implement this algorithm myself?

Alex
  • 12,578
  • 15
  • 99
  • 195
  • 4
    You need to do it yourself. If you need to do this for deep learning, you can use the [blob](http://docs.opencv.org/3.1.0/da/d16/classcv_1_1dnn_1_1Blob.html) class (as well as the whole dnn module) – Miki Sep 02 '17 at 21:56

3 Answers3

0

If you wish to treat the underlying data differently, then you can use reshape. The data is stored as BGRBGRBGR....

Otherwise you will have to shuffle the data yourself.
cv::reshape and cv::minChannels may be handy for this.

Adi Shavit
  • 16,743
  • 5
  • 67
  • 137
0

You can emulate it. I have not tested the code but something like this should do:

cv::Mat frame (1000, 1000, CV_8UC3) = cv::imread("image.jpg", -1);
int sizes_inputs[] = { 3, 1000, 1000 };
cv::Mat out_image(3, sizes_inputs, CV_8UC);

cv::Mat slices[] = {cv::Mat(1000, 1000, CV_8UC, out_image.ptr()),
                    cv::Mat(1000, 1000, CV_8UC, out_image.ptr() + 1000*1000),
                    cv::Mat(1000, 1000, CV_8UC, out_image.ptr() + 1000*1000*2)};
cv::split(frame, slices);
Andrey Kamaev
  • 29,582
  • 6
  • 94
  • 88
0

Please check the answer here: C++ OpenCV transpose/permute image axes

I tried with the following code:

cv::Mat a = cv::imread("red.png");
auto b = a.clone();
std::vector<cv::Mat> planes =
{
    cv::Mat(a.rows, a.cols, CV_8U, b.ptr(0)), 
    cv::Mat(a.rows, a.cols, CV_8U, b.ptr(0) + a.rows * a.cols),
    cv::Mat(a.rows, a.cols, CV_8U, b.ptr(0) + a.rows * a.cols * 2)
};
cv::split(a, planes);

By watching the value of a and b, the buffer seemed to be correct. enter image description here enter image description here

General Grievance
  • 4,555
  • 31
  • 31
  • 45