简体   繁体   中英

OpenCV: Convert an image to C++ array

I want to read an 3-channel RGB image in opencv and convert it to a linear C++ float array. Sounds simple, but still I'm struggling. I tried it with this code, but for some reason it's giving me a segmentation fault

  cv::Mat rgb_image;
  cv::imread(filename.c_str(), cv::IMREAD_COLOR).convertTo(rgb_image,  CV_32FC3, (1./255.));

  float *rgb_data = new float(rgb_image.rows * rgb_image.cols * rgb_image.channels());
  int counter = 0;
  for (int z = 0; z < rgb_image.channels(); z++)
    for (int i = 0; i < rgb_image.rows; i++)
      for (int j = 0; j < rgb_image.cols; j++){
        rgb_data[counter] = rgb_image.at<cv::Vec3f>(i,j)[z] ;
        counter++;
      }

Does anyone see what's going wrong?
Is there an easier way of doing it?
I know there are stackoverflow-examples for converting a cv::Mat into an std::vector , would something similar possible for a C++ array? Output dimensions should be [Rows x Cols x Channel]

You have two problems:

  1. Pointed by rafix07: use [] instead of ()

  2. rgb_image.at(i,j)[z] gives 3 floats not 1

I would suggest to use std::memcpy

float *rgb_data = new float(rgb_image.rows * rgb_image.cols * rgb_image.channels()); // Dst
float* dataPointer = reinterpret_cast<float*>(rgb_image.data); // Src
// pointer from, pointer two, size in bytes
std::memcpy(rgb_data, dataPointer, rgb_image.rows * rgb_image.cols * rgb_image.channels() * sizeof(float));

it is optimized and probably better than the loops :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM