#include<iostream>
#include<cstdio>
#include<cmath>
#define H 1210
#define W 1240

using namespace std;

int main()
{
	unsigned char* grey;
	// 存灰度值的数组
	grey = new unsigned char[H * W];
	FILE* filetest;
	//读取文件
	fopen_s(&filetest, "E:\\Digital image process\\lab-1\\第一次上机实验数据\\test.raw", "rb");
	fread(grey, sizeof(unsigned char), H * W, filetest);

	int i, j;
	int* Pi_number = new int[256];
	for (i = 0; i < 256; i++) {
		Pi_number[i] = 0;
	}
	for (i = 0; i < H; i++) {
		for (j = 0; j < W; j++) {
			Pi_number[grey[i * W + j]]++;
		}
	}
	float* Pi = new float[256];
	for (i = 0; i < 256; i++) {
		Pi[i] = (float)Pi_number[i] / (H * W);
	}

	//计算均值和标准差
	float mean = 0;
	for (i = 0; i < 256; i++) {
		mean += (float)i * Pi[i];
	}

	float variance = 0;
	for (i = 0; i < 256; i++) {
		variance += Pi[i] * (i - mean) * (i - mean);
	}
	float stdvar = sqrt(variance);

	FILE* fileout;

	fopen_s(&fileout, "E:\\Digital image process\\lab-1\\第一次上机实验数据\\result.txt", "w");

	fprintf(fileout, "完成人：测绘2401 24110901003 毕爽爽 \n");
	fprintf(fileout, "均值：%f，标准差：%f\n", mean, stdvar);
	for (i = 0; i < 256; i++) {
		fprintf(fileout, "灰度值为%d的像素个数：%d,频率：%f\n", i, Pi_number[i], Pi[i]);
	}

	fclose(filetest);
	fclose(fileout);
}