单通道8位数据 存储到Opencv Mat格式有问题

需求:图像是8位,单通道图像,想把图像用jpeg格式保持下来。假定图像宽640,高400
通过Mat中遍历方式,来将文件中读取的8位存储到Mat中。(不用imread读取,因为还有16位单通道图像,我现在暂时只了解这个方式可以遍历读取,8位跑通,16也会跑通,若是有人知道16bit 单通道数据直接可以转换成jpeg图像也可以)
现在遇到情况是imwrite或是imshow都不能显示正确原来的图片。

    std::ifstream t;
    int length = 0;  
    t.open("binaryimgtest.bmp");      // open input file  
    t.seekg(0, std::ios::end);    // go to the end  
    length = t.tellg();           // report location (this is the length)  
    t.seekg(0, std::ios::beg);    // go back to the beginning  
    char *bufferData = new char[length];    // allocate memory for a buffer of appropriate dimension  
    t.read(bufferData, length);       // read the whole file into the buffer  
    t.close();                    // close file handle

    Mat mat(400, 640, CV_8UC1);//Mat mat(400, 640, CV_16UC1);
    int ch = mat.channels();
    unsigned char bufferVal = 0;//unsigned short bufferVal = 0;
    unsigned char cutVal = 0;//unsigned short cutVal = 0;

    for (size_t row = 0; row < 400; ++row) {
        for (size_t col = 0; col < 640; ++col) {
            bufferVal = *(((unsigned char*)bufferData + row * 640 + col));
            //cutVal = bufferVal & 0x0FFF;
            mat.at<unsigned char>(row, col) = bufferVal;
        }
    }
    delete [] bufferData;
    bufferData = 0;
    imshow("test", mat);
    imwrite("binaryimgtest_tmp.jpg", mat);

求教ing,若是有人知道16bit 单通道数据直接可以转换成jpeg图像也可以

mat文件文件中会有很多变量,每个变量有不同的数据格式,视频帧是一个m*n*3*k的数组

mat文件文件中会有很多变量,每个变量有不同的数据格式,视频帧是一个m*n*3*k的数组

mat文件中会有很多变量,每个变量有不同的数据格式,视频帧是一个m*n*3*k的数组

mat文件文件中会有很多变量,每个变量有不同的数据格式,视频帧是一个m*n*3*k的数组

mat文件文件中会有很多变量,每个变量有不同的数据格式,视频帧是一个m*n*3

mat文件文件中会有很多变量,每个变量有不同的数据格式

mat文件中会有很多变量,每个变量有不同的数据格式,,试试看

mat文件中会有很多变量,每个变量有不同的数据格式,,试试看

mat文件中会有很多变量,每个变量有不同的数据格式,视频帧是一个m*n*3*k的数组就可以了........

bmp文件里有文件头、信息头、调色板、然后才是实际数据,不能简单地从头开始读取吧,opencv 的imread方法肯定不止简单地吧图像灰度读入,还有图像长宽之类的信息都会组织进去,建议直接用imread方法,对bmp文件的介绍可以参考读取BMP文件并显示出来(C++实现)