Opencv从相机数据创建mat

opencv create mat from camera data

本文关键字:创建 mat 数据 相机 Opencv      更新时间:2023-10-16

在我的程序中,我有从相机中获取图像的函数,并且应该将OpenCV Mat结构中的所有数据打包。从相机我得到宽度,高度和unsigned char*到图像缓冲区。我的问题是如何从这些数据创建Mat,如果我有全局Mat变量。Mat结构的类型我取的是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: %un", image.size().width);
    printf("height: %un", image.size().height);
    image_.create(Size(image.size().width, image.size().height), CV_8UC1);
    image_ = image.clone();
    printf("width: %un", image_.size().width);
    printf("height: %un", image_.size().height);
}

当我测试我的程序时,我得到imagewidthheight,但我的全局Mat image_widthheight0。我如何才能把数据在我的全局Mat变量正确?

谢谢。

不幸的是,clone()copyTo()都没有成功地将宽度/高度的值复制到另一个Mat.至少在OpenCV 2.3上!真遗憾,真的。

但是,您可以通过使函数返回Mat来解决这个问题并简化代码。这样你就不需要一个全局变量:

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