c++ - 如何从 MNIST 数字数据库中读取像素并创建 iplimage

标签 c++ opencv ocr

抱歉,这可能有点重复,但我无法修复它。我参与了手写 OCR 应用程序。我在这里使用 MNIST 数字数据库进行训练。我使用以下代码 here用于从数据库中读取像素并重新创建图像。程序不会给出任何错误,但它会给出无意义的图像(全黑且像素图案不清晰)作为输出。有人可以解释原因吗?请帮忙

这是我的代码

int reverseInt(int i) {
unsigned char c1, c2, c3, c4;
c1 = i & 255;
c2 = (i >> 8) & 255;
c3 = (i >> 16) & 255;
c4 = (i >> 24) & 255;
return ((int)c1 << 24) + ((int)c2 << 16) + ((int)c3 << 8) + c4;
}

void create_image(CvSize size, int channels, unsigned char* data[28][28], int imagenumber) {
string imgname; ostringstream imgstrm;string fullpath;
imgstrm << imagenumber;
imgname=imgstrm.str();
fullpath="D:\\"+imgname+".jpg";

IplImage *imghead=cvCreateImageHeader(size, IPL_DEPTH_16S, channels);
imghead->imageData=(char *)data;
cvSaveImage(fullpath.c_str(),imghead);  
}
int main(){
ifstream file ("D:\\train-images.idx3-ubyte",ios::binary);
if (file.is_open())
{
    int magic_number=0; int number_of_images=0;int r; int c;
    int n_rows=0; int n_cols=0;CvSize size;unsigned char temp=0;

    file.read((char*)&magic_number,sizeof(magic_number)); 
    magic_number= reverseInt(magic_number);

    file.read((char*)&number_of_images,sizeof(number_of_images));
    number_of_images= reverseInt(number_of_images);

    file.read((char*)&n_rows,sizeof(n_rows));
    n_rows= reverseInt(n_rows);
    file.read((char*)&n_cols,sizeof(n_cols));
    n_cols= reverseInt(n_cols);
    unsigned char *arr[28][28];


    for(int i=0;i<number_of_images;++i)
    {
        for(r=0;r<n_rows;++r)
        {
            for(c=0;c<n_cols;++c)
            {                 
                file.read((char*)&temp,sizeof(temp));
                arr[r][c]= &temp;
            }           
        }
        size.height=r;size.width=c;
        create_image(size,1, arr, i);
    }
}
return 0;
}

最佳答案

你有:

unsigned char temp=0;
...
file.read((char*)&temp,sizeof(temp));

这样,您就可以将一个字节读入单个字符,并用文件中的每个后续字节覆盖它。 当您这样做时:

create_image(size,3, &temp, i);

temp 只有一个字符长,只包含文件中的最后一个字节,因此您的图像最终会成为 temp 之后内存中的任何内容。 您需要分配一个数组来保存图像数据,并在用数据填充它时递增一个指向它的指针。

您还创建了一个 3 channel 图像,但 MNIST 数据只是单 channel ,对吧?

此外,

imghead->imageData=(char *)data;

应该是

cvSetData(imghead, data, size.width)

unsigned char *arr[28][28];

应该是

unsigned char arr[28][28];

关于c++ - 如何从 MNIST 数字数据库中读取像素并创建 iplimage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16871512/

相关文章:

python - 无法在OpenCV中关闭视频窗口

opencv - 计算机视觉备忘单或流程图

用于 OCR 的 iOS UIImage 二值化 - 处理具有不同亮度的图像

c++ - 如何扩展 STL 类以拥有自己的方法?

c++ - “struct _ntl_gbigint_body”在哪里定义?

opencv - 具有测量的外部参数的立体声整流

opencv - 从图像中识别令人难以置信的/拼字游戏字母

c++ - 使用线程读取两个文件并输出到另一个文件

c++ - 防止 MFC 应用程序将光标更改回默认图标

python - 修复 "ModuleNotFoundError: No module named ' fsns'"in google colab for Attention ocr