11

in my programm I have function that takes the image from camera and should pack all data in OpenCV Mat structure. From the camera I get width, height and unsigned char* to the image buffer. My Question is how I can create Mat from this data, if I have global Mat variable. The type for Mat structure I took CV_8UC1.

Mat image_;

function takePhoto() {
    unsigned int width = getWidthOfPhoto();
    unsinged int height = getHeightOfPhoto();
    unsinged char* dataBuffer = getBufferOfPhoto();
    Mat image(Size(width, height), CV_8UC1, dataBuffer, Mat::AUTO_STEP);

    printf("width: %u\n", image.size().width);
    printf("height: %u\n", image.size().height);

    image_.create(Size(image.size().width, image.size().height), CV_8UC1);
    image_ = image.clone();

    printf("width: %u\n", image_.size().width);
    printf("height: %u\n", image_.size().height);
}

When I test my program, I get right width and height of image, but width and height of my global Mat image_ is 0. How I can put the data in my global Mat varible correctly?

Thank you.

M.K.
  • 640
  • 1
  • 10
  • 23

1 Answers1

17

Unfortunately, neither clone() nor copyTo() successfully copy the values of width/height to another Mat. At least on OpenCV 2.3! It's a shame, really.

However, you could solve this issue and simplify your code by making the function return the Mat. This way you won't need to have a global variable:

Mat takePhoto() 
{
    unsigned int width = getWidthOfPhoto();
    unsigned int height = getHeightOfPhoto();
    unsigned char* dataBuffer = getBufferOfPhoto();
    Mat image(Size(width, height), CV_8UC1, dataBuffer, Mat::AUTO_STEP);
    return Mat;
}

int main()
{
    Mat any_img = takePhoto();
    printf("width: %u\n", any_img.size().width);
    printf("height: %u\n", any_img.size().height);
}
mehfoos yacoob
  • 408
  • 3
  • 9
karlphillip
  • 92,053
  • 36
  • 243
  • 426
  • Hi Karlphilip, Thank you so much for contributing to stackoverflow and helping us. im new to OpenCV, and find your answer quite useful for the the project I am working right now. I have a quick question, what is the difference between : cv::Mat and cvMat and cvCreateMat() ? – user261002 Apr 13 '12 at 11:21
  • 3
    `cv::Mat` is the Mat type for the C++ interface of OpenCV. `cvMat` is for the C interface. `cvCreateMat()` creates a `cvMat` in the C interface. Let's not hijack this thread any further, if you have questions you are free to ask them in new threads. See you around. – karlphillip Apr 13 '12 at 12:37