izi
izi

Reputation: 59

Understanding openCV code snippet

I have a question about this peace of code.

...............
 cv::Mat image;
 image = cv::imread(filename.c_str(), CV_LOAD_IMAGE_COLOR);
   if (image.empty()) {
   std::cerr << "Couldn't open file: " << filename << std::endl;
   exit(1);
 }

 cv::cvtColor(image, imageRGBA, CV_BGR2RGBA);


 imageGrey.create(image.rows, image.cols, CV_8UC1);

 *inputImage = (uchar4 *)imageRGBA.ptr<unsigned char>(0);
 *greyImage  = imageGrey.ptr<unsigned char>(0);

As I understand we create a openCV mat object. Read the image into it. But why we use filename.c_str()? instead of just filename? And why we convert from BGR to RGBA? cv::cvtColor(image, imageRGBA, CV_BGR2RGBA); I read in the documentation that imread reads the image as RGB not BGR. The most confusing for we is this part:

  *inputImage = (uchar4 *)imageRGBA.ptr<unsigned char>(0);
  *greyImage  = imageGrey.ptr<unsigned char>(0);

What's happening here? why we need all this casts? I know this is a lot of question, but I really want to know whats happening here.)

Upvotes: 1

Views: 1029

Answers (1)

ypnos
ypnos

Reputation: 52397

  1. imread takes a const char* as first argument and you cannot pass a std::string directly to it
  2. OpenCV stores matrices as BGR. So also imread adheres to this channel order (documentation might be misleading, don't confuse image format read (RGB) versus internal representation (BGR)). Based on your cuda tag I guess somebody wants to pass the image data to the GPU. GPUs typically work with RGBA format. It is not only about BGR<->RGB but also about having four channels in the interleaved format.
  3. The Mat::ptr() is templated (it is not casting!) because Mat hides the datatype from you. The code is risky, as it just assumes imread would create a Mat_<uchar> and so this is the right type to access. It would be better to start with a cv::Mat_<uchar> in the first place, then use Mat_<T>::operator[] to get a pointer to the first row etc.
  4. I don't know what comes next in your code but there might be a bug if the stride (step) is not considered.

Upvotes: 5

Related Questions