Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

c++ - opencv create mat from camera data

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
", image.size().width);
    printf("height: %u
", image.size().height);

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

    printf("width: %u
", image_.size().width);
    printf("height: %u
", 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
", any_img.size().width);
    printf("height: %u
", any_img.size().height);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...