Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/136.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ OpenCV Mat::数据写入文件并读取_C++_Opencv_Io_Binaryfiles - Fatal编程技术网

C++ OpenCV Mat::数据写入文件并读取

C++ OpenCV Mat::数据写入文件并读取,c++,opencv,io,binaryfiles,C++,Opencv,Io,Binaryfiles,当我试图写一个用OpenCV从相机上捕获的图像数据,并将其读出时,事情并没有进展顺利。我尝试了很多格式,比如CV_8UC3和CV_UC1灰度图像 首先,我从相机上拍摄了一幅图像(640*480),并将数据保存到一个文件中 VideoCapture cap(0); namedWindow("test",0); namedWindow("gray",0); FILE *f=fopen("data.txt","wt+"); while(1) { Mat frame; cap>

当我试图写一个用OpenCV从相机上捕获的图像数据,并将其读出时,事情并没有进展顺利。我尝试了很多格式,比如CV_8UC3和CV_UC1灰度图像

首先,我从相机上拍摄了一幅图像(640*480),并将数据保存到一个文件中

VideoCapture cap(0);

namedWindow("test",0);
namedWindow("gray",0);

FILE *f=fopen("data.txt","wt+");

while(1)
{
    Mat frame;
    cap>>frame;
    imshow("test", frame);

    //Mat temp(1, 1, CV_8UC3);
       Mat gray;

    if(waitKey(30) >= 0) 
    {
        cvtColor(frame, gray, CV_BGR2GRAY);
        imshow("gray", gray);
        waitKey();
        fwrite(gray.data, sizeof(unsigned char), 640*480,f);
        break;
    }
}

fclose(f);
return 0;
然后在另一个程序中,我尝试读出它们,如:

FILE *f = fopen("data.txt", "rt");
unsigned char* buffer;
size_t result;
buffer = (unsigned char*)malloc(sizeof(unsigned char)*640*480);

result = fread(buffer, sizeof(unsigned char), 640*480,f);

fclose(f);

Mat image(640, 480, CV_8UC1, buffer);

namedWindow("test", 0);
imshow("test", image);
waitKey();
那个么图像就会出错

谢谢您的建议。

您不能以txt模式保存二进制数据

应该是

FILE *f=fopen("data.txt","wb");
而不是:

FILE *f=fopen("data.txt","wt+");  
// btw, what's the + for ? appending does not make any sense here
读取操作也是如此。(“rb”代替“rt”)


但再说一遍,为什么会发生这些事情呢?使用内置的东西:


谢谢你的建议。图像不正确(比以前好多了),我把它改成wb,rb心情。我想知道图像是否真的是CV_8UC1 type.OMG,我在更改图像后立即得到了一些内容(640480,CV_8UC1,buffer);至图像(480640,CV_8UC1,缓冲器);先是排,然后是科尔斯。真是个错误,非常感谢!