从指定文件夹中读入数据,并绘制直方图

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include<fstream>
#include<iomanip>
#include<iostream>
#include <opencv/cv.h>
#include <opencv/highgui.h> 
using namespace std;

int main()
{
     int hist[256] = {0};//存放直方图数据的数组
      /*将data.txt中的数据读到workspace中来*/
     ifstream infile;
     infile.open ("data.txt");
     //data.txt 中存放的数据为120*96 的数据,该数据为像素数据,值域为:[0,256]
	int   arr[120][96];   //矩阵120*96
	int   v;
	if (infile.is_open())
    {
      for(int i=0;i<120;i++)
		for(int j=0;j<96;j++)
		{
			infile>>arr[i][j];
		    v = arr[i][j];
			hist[v]++;
		}

	  infile.close();
	}
	else
      cout << "Error opening file";
	
	//找出数据的最大值
	int max=0;
	for(int i=0;i<256;i++)
	{
		if(hist[i]>max)
		{
			max=hist[i];
		}
	}

	//创建直方图
	IplImage* dst = cvCreateImage(cvSize(400,300),8,3);
	cvSet(dst,cvScalarAll(255),0);
	double bin_width=(double)dst->width/256;
	double bin_unith=(double)dst->height/max;

	//绘制直方图
	for(int i=0;i<256;i++)
	{
		CvPoint p0=cvPoint(i*bin_width,dst->height);
		CvPoint p1=cvPoint((i+1)*bin_width,dst->height-hist[i]*bin_unith);
		cvRectangle(dst,p0,p1,cvScalar(0,255),-1,8,0);
	}

	//显示直方图
	cvNamedWindow("dst",1);
	cvShowImage("dst",dst);

	//保存直方图
	cvSaveImage( "hist.jpg",dst);

	cvWaitKey(0); 

	//注销直方图
	cvDestroyAllWindows();
	cvReleaseImage(&dst);

	return 0;
}

你可能感兴趣的:(从指定文件夹中读入数据,并绘制直方图)