我正试图通过论坛的帮助代码实现一种感兴趣的KNN算法。代码如下。
#include <opencv\cv.h>
#include <opencv\ml.h>
#include <opencv\highgui.h>
#include <opencv\cxcore.h>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
using namespace std;
using namespace cv;
//typedef unsigned char BYTE;
int readFlippedInteger(FILE *);
int main()
{
FILE *fp = fopen("D:\\KNN\\train-images.idx3-ubyte", "rb");
FILE *fp2 = fopen("D:\\KNN\\train-labels.idx1-ubyte", "rb");
if(!fp || !fp2)
{
cout<<"Files not Found"<<endl;
return 0;
}
int magicNumber = readFlippedInteger(fp);
int numImages = readFlippedInteger(fp);
int numRows = readFlippedInteger(fp);
int numCols = readFlippedInteger(fp);
fseek(fp2, 0x08, SEEK_SET);
int size = numRows*numCols;
CvMat *trainingVectors = cvCreateMat(numImages, size, CV_32FC1);
CvMat *trainingLabels = cvCreateMat(numImages, 1, CV_32FC1);
//BYTE *temp = new BYTE[size];
unsigned char *temp = (unsigned char *) malloc(size);
unsigned char tempClass=0;
for(int i=0; i < numImages; i++)
{
fread((void*)temp, size, 1, fp);
fread((void*)(tempClass), sizeof(unsigned char*), 1, fp2);
trainingLabels->data.fl[i] = tempClass;
for(int k=0; k < size; k++)
trainingVectors->data.fl[i*size+k] = temp[k];
}
KNearest knn(trainingVectors, trainingLabels);
printf("Maximum k: %d\n", knn.get_max_k());
fclose(fp);
fclose(fp2);
cvReleaseMat(&trainingVectors);
cvReleaseMat(&trainingLabels);
return 0;
}
int readFlippedInteger(FILE *fp)
{
int ret = 0;
unsigned char *temp;
temp = (unsigned char*)(ret);
fread(&temp[3], sizeof(unsigned char*), 1, fp);
fread(&temp[2], sizeof(unsigned char*), 1, fp);
fread(&temp[1], sizeof(unsigned char*), 1, fp);
fread(&temp[0], sizeof(unsigned char*), 1, fp);
return ret;
}
我使用unsigned char而不是BYTE,我认为应该做同样的工作。如果我在这里错了,请纠正我。
尽管如此,我不是编程方面的专家,但是当我运行代码时,我得到了这个错误
* K-Nearest Neighbour.exe中0x000007FEE68F7450(msvcr110d.dll)的未处理异常:0xC0000005:访问冲突写入位置 0x0000000000000003
有人可以帮我构建这段代码吗。谢谢
答案 0 :(得分:0)
你错过了&#39;地址 - &#39;运算符,sizeof似乎错了:
int readFlippedInteger(FILE *fp)
{
int ret = 0;
unsigned char *temp = (unsigned char*)(&ret);
fread(&temp[3], sizeof(unsigned char), 1, fp);
fread(&temp[2], 1, 1, fp); // should be equivalent to above
...
}
另一个问题可能是假设int
是4个字节,因为您正在使用64位进行编译,这从错误消息中可以看出。