예제 #1
0
void ksampleEtest(double *x, int *byrow,
                  int *nsamples, int *sizes, int *dim,
                  int *R, double *e0, double *e, double *pval)
{
    /*
      exported for R energy package: E test for equal distributions
      x         the pooled sample (or distances)
      *byrow    logical, TRUE if x is stored by row
                pass x=as.double(t(x)) if *byrow==TRUE
      *nsamples number of samples
      *sizes    vector of sample sizes
      *dim      dimension of data in x (0 if x is distance matrix)
      *R        number of replicates for permutation test
      *e0       observed E test statistic
      e         vector of replicates of E statistic
      *pval     approximate p-value
    */

    int    b, ek, i, k;
    int    B = (*R), K = (*nsamples), d=(*dim), N;
    int    *perm;
    double **data, **D;

    N = 0;
    for (k=0; k<K; k++)
        N += sizes[k];
    perm = Calloc(N, int);
    for (i=0; i<N; i++)
        perm[i] = i;
    D   = alloc_matrix(N, N);      /* distance matrix */
    if (d > 0) {
        data = alloc_matrix(N, d); /* sample matrix */
        vector2matrix(x, data, N, d, *byrow);
        distance(data, D, N, d);
        free_matrix(data, N, d);
    }
    else
        vector2matrix(x, D, N, N, *byrow);

    *e0 = multisampleE(D, K, sizes, perm);

    /* bootstrap */
    if (B > 0) {
        ek = 0;
        GetRNGstate();
        for (b=0; b<B; b++) {
            permute(perm, N);
            e[b] = multisampleE(D, K, sizes, perm);
            if ((*e0) < e[b]) ek++;
        }
        PutRNGstate();
        (*pval) = ((double) (ek + 1)) / ((double) (B + 1));
    }

    free_matrix(D, N, N);
    Free(perm);
}
예제 #2
0
//This function is used to recognize continuous SLR in a off-line way. 
//Since the data should be read in all at once, the class gcmCont is not necessary used. 
int gcm::patchRun_continuous_PQ(vector<SLR_ST_Skeleton> vSkeletonData, vector<Mat> vDepthData, vector<IplImage*> vColorData, 
								int *rankIndex, double *rankScore)
{
	int window = 40;
	int kernelFeatureDim = NClass*NTrainSample;
	//Computing features
	cout<<"Computing features..."<<endl;
	oriData2Feature(vSkeletonData, vDepthData, vColorData);

	//////////////////////////////////////////////////////////////////////////
	//Compute P and Q all at once.
	vector<double*> P;
	vector<double**> Q;
	cout<<"Computing P and Q..."<<endl;

	//computePQ(P, Q, vColorData.size());
	//white
	for (int d=0; d<nDimension; d++)
	{
		double dimAve = 0.0;
		for (int f=0; f<nFrames; f++)
		{
			dimAve += feature_ori[f][d];
		}
		dimAve /= nFrames;
		for (int f=0; f<nFrames; f++)
		{
			feature_ori[f][d] -= dimAve;
		}
	}

	//Compute P and Q.
	int nFrames_PQ = vColorData.size();
	for (int i=0; i<nFrames_PQ; i++)
	{
		cout<<"Current "<<i<<"/"<<nFrames_PQ<<endl;
		//Compute P
		double* tempP = new double[featureDim];
		for (int j=0; j<featureDim; j++)
		{
			tempP[j] = 0;
			for (int k=0; k<i; k++)
			{
				tempP[j] += feature_ori[k][j];
			}
		}
		P.push_back(tempP);    //To release it when reaching the end of a sentence 

		//Compute Q
		double** tempQ;
		tempQ = newMatrix(featureDim, featureDim);
		for (int f1=0; f1<featureDim; f1++)
		{
			for (int f2=0; f2<featureDim; f2++) 
			{
				tempQ[f1][f2] = 0;
				for (int l=0; l<i; l++)
				{
					tempQ[f1][f2] += feature_ori[f1][l]*feature_ori[f2][l];
				}
			}
		}
		Q.push_back(tempQ);      //To release it when reaching the end of a sentence 
	}
	//////////////////////////////////////////////////////////////////////////	
	
	double** C = newMatrix(featureDim, featureDim);
	double* p_temp = new double[featureDim];  //The deltaP
	double** Pm = newMatrix(featureDim, featureDim);
	for (int i=window; i<vColorData.size()-window; i++)
	{
		int begin = i-window/2;
		int end = i+window/2;

		//The matrix from p
		for (int pf=0; pf<featureDim; pf++)
		{
			p_temp[pf] = P[end][pf]-P[begin][pf];
		}
		vector2matrix(p_temp, p_temp, Pm,featureDim);

		//Compute the covariance matrix
		for (int l=0; l<featureDim; l++)
		{
			for (int m=0; m<featureDim; m++)
			{
				C[l][m] = ((Q[end][l][m]-Q[begin][l][m])-Pm[l][m]/(end-begin+1))/(end-begin);
			}
		}

		//Regularization term added
		for (int d=0; d<nDimension; d++)
		{
			for (int d2=0; d2<nDimension; d2++)
			{
				//C[d][d2] /= nFrames;
				if (d == d2)
				{
					C[d][d2] += 0.001;
				}
			}
		}

		//The subspace matrix
		PQsubspace(C, gcm_subspace);

		//For debug
		ofstream foutDebug;
		foutDebug.open("..\\output\\debug.txt");
		for (int i=0; i<featureDim; i++)
		{
			for (int j=0; j<subSpaceDim; j++)
			{
				foutDebug<<gcm_subspace[i][j]<<"\t";
			}
			foutDebug<<"\n";
		}
		foutDebug << flush;
		foutDebug.close();

		//The SVM classification
		x[0].index = 0;
		for (int j=0; j<kernelFeatureDim; j++)
		{
			subMatrix(subFeaAll_model, subFea1, 0, featureDim, j*subSpaceDim, subSpaceDim);
			x[j+1].value = myGcmKernel.Frobenius(subFea1, gcm_subspace, featureDim, subSpaceDim);
			x[j+1].index=j+1;
		}
		x[kernelFeatureDim+1].index=-1;

		int testID = svm_predict_probability(myModel, x, prob_estimates);
		cout<<"Frame: "<<i<<"/"<<vColorData.size()-window<<" Result: "<<testID<<endl;
	}
	delete[] p_temp;
	deleteMatrix(Pm,featureDim);
	deleteMatrix(C, featureDim);

	//To delete P and Q


	return 1;

// 	gcmSubspace();
// 
// 	x[0].index = 0;
// 	for (int j=0; j<kernelFeatureDim; j++)
// 	{
// 		subMatrix(subFeaAll_model, subFea1, 0, featureDim, j*subSpaceDim, subSpaceDim);
// 		x[j+1].value = myGcmKernel.Frobenius(subFea1, gcm_subspace, featureDim, subSpaceDim);
// 		x[j+1].index=j+1;
// 	}
// 	x[kernelFeatureDim+1].index=-1;
// 
// 	int testID = svm_predict_probability(myModel, x, prob_estimates);
// 
// 	//Sort and get the former 5 ranks. 
// 	vector<scoreAndIndex> rank;
// 	for (int i=0; i<myModel->nr_class; i++)
// 	{
// 		scoreAndIndex temp;
// 		temp.index = myModel->label[i];
// 		temp.score = prob_estimates[i];
// 		rank.push_back(temp);
// 	}
// 	sort(rank.begin(),rank.end(),comp);
// 
// 	for (int i=0; i<5; i++)
// 	{
// 		rankIndex[i] = rank[i].index;
// 		rankScore[i] = rank[i].score;
// 	}
// 
// 
// 	//Release
// 	nFrames = 0;
// 
// 	return testID;
}
int main(int argc, char const *argv[])
{
	FILE*fp,*image;
	unsigned char** red,**green,**blue, *image_contents_rgb, *image_contents_rgbt;
	int i, ERROR;
	Header1 header1;
	Header2 header2;

	if(argc!= 2)												
	{
	  /* syntax error check*/
		printf("\n The format is ./quantizer [file-name]");
		return -1;
	}

	if((fp = fopen(argv[1],"rb"))== NULL)
	{
	  /* open the .bmp file for reading*/
		printf("\n Error opening the file specified. Please check if the file exists !!\n");
		fclose(fp);
		return -1;
	}

	if(fread(&header1,sizeof(header1),1,fp)!=1)				
	{
	  /* Read the primary header from the bmp file */
		printf("\n Error reading header1 \n");
		fclose(fp);
		return -1;
	}

	if(header1.type!= 19778)
	{
	  /* check if its a valid bmp file*/
		printf("\n Not a bmp file. Exiting !! \n");
		fclose(fp);
		return -1;
	}

	if(fread(&header2,sizeof(header2),1,fp)!=1 )
	{
		printf("\n Error reading header 2");
		fclose(fp);
		return -1;
	} 

	image_contents_rgb = (unsigned char*)malloc(sizeof(char) * header2.imagesize); 
	image_contents_rgbt = (unsigned char*)malloc(sizeof(char) * header2.imagesize);	/*allocate memory to store image data*/

	fseek(fp,header1.offset,SEEK_SET); 	

	if((ERROR=fread(image_contents_rgb,header2.imagesize,1,fp))!=1)
	{
		printf("\nError reading contents\n");
		free(image_contents_rgb);
		fclose(fp);
		return -1;
	} 

	fclose(fp);

	red = (unsigned char**)malloc(sizeof(char*) * header2.height);
	green = (unsigned char**)malloc(sizeof(char*) * header2.height);
	blue = (unsigned char**)malloc(sizeof(char*) * header2.height);

	for(i=0 ; i<header2.height ;i++)
	{
		red[i] = (unsigned char*)malloc( sizeof(char) * header2.width);
		green[i]= (unsigned char*)malloc( sizeof(char) * header2.width);
		blue[i]= (unsigned char*)malloc( sizeof(char) * header2.width);
	}
	
	vector2matrix(red,green,blue,image_contents_rgb,header2.height,header2.width); 	/* call to store image contents as matrix */
	matrix2vector_rgb(red,green,blue,image_contents_rgbt,header2.height,header2.width); /*convert back from matrix to vector*/
	snr(image_contents_rgb, image_contents_rgbt, header2.height, header2.width);        /* Calulate PSNR*/

	if((image = fopen("quant_image","wb")) == NULL)
	{
		printf("\n ERROR opening the file to write quantized image !!\n");
		fclose(image);
		return -1;
	}

	if(fwrite(&header1,sizeof(header1),1,image)!= 1)
	{
		printf("\n ERROR writing header 1 into destination file !!\n");
		fclose(image);
		return -1;
	}

	if(fwrite(&header2,sizeof(header2),1,image)!= 1)
	{
		printf("\n ERROR writing header 2 into destination file !! \n");
		fclose(image);
		return -1;
	}

	fseek(image, header1.offset, SEEK_SET);

	if(fwrite(image_contents_rgbt,header2.imagesize,1,image)!=1)
	{
	  /*Store the edited RGB components into a bmp file*/
		printf("\n ERROR writing image contents into destination file \n");
		fclose(image);
		return -1;
	}

	free(red);
	free(green);
	free(blue);
	free(image_contents_rgb);
	fclose(image);
	return 0;
}
예제 #4
0
파일: dcov.c 프로젝트: xiangdiuxiu/CodeShop
void undCOV(double *x, double *y, int *byrow, int *dims,
              double *index, double *idx, double *DCOV) {
    /*  computes dCov(x,y), dCor(x,y), dVar(x), dVar(y)
        V-statistic is n*dCov^2 where n*dCov^2 --> Q
        dims[0] = n (sample size)
        dims[1] = p (dimension of X)
        dims[2] = q (dimension of Y)
        dims[3] = dst (logical, TRUE if x, y are distances)
        index : exponent for distance
        idx   : index vector, a permutation of sample indices
        DCOV  : vector [dCov, dCor, dVar(x), dVar(y)]
     */

    int    j, k, n, n2, p, q, dst;
    double **Dx, **Dy, **A, **B;
    double V;

    n = dims[0];
    p = dims[1];
    q = dims[2];
    dst = dims[3];

    if (*byrow == FALSE) {
        /* avoid this step: use as.double(t(x)) in R */
        roworder(x, byrow, n, p);
        *byrow = FALSE;  /* false for y */
        roworder(y, byrow, n, q);
    }
    /*So why do you write codes above?*/

    /* critical to pass correct flag dst from R */
    Dx = alloc_matrix(n, n);//n:
    Dy = alloc_matrix(n, n);
    if (dst) {
		vector2matrix(x, Dx, n, n, 1);
		vector2matrix(y, Dy, n, n, 1);
	}
	else {
		Euclidean_distance(x, Dx, n, p);
		Euclidean_distance(y, Dy, n, q);
	}
	index_distance(Dx, n, *index);
	index_distance(Dy, n, *index);

    A = alloc_matrix(n, n);
    B = alloc_matrix(n, n);
    Akl(Dx, A, n);
    Akl(Dy, B, n);
    free_matrix(Dx, n, n);
    free_matrix(Dy, n, n);

    n2 = ((double) n) * n;

    /* compute dCov(x,y), dVar(x), dVar(y) */
    for (k=0; k<4; k++)
        DCOV[k] = 0.0;
    for (k=0; k<n; k++)
        for (j=0; j<n; j++) {
	  //What I have changed.
	  if(k != j){
	    DCOV[0] += A[k][j]*B[k][j];
	    DCOV[2] += A[k][j]*A[k][j];
	    DCOV[3] += B[k][j]*B[k][j];
	  }else{
	    DCOV[0] -= A[k][j]*B[k][j] * (2 / (n-2));
	    DCOV[2] -= A[k][j]*A[k][j] * (2 / (n-2));
	    DCOV[3] -= B[k][j]*B[k][j] * (2 / (n-2));
	  }
        }

    for (k=0; k<4; k++) {
      DCOV[k] /= ((double) n) * (n - 3);
        if (DCOV[k] > 0)
            DCOV[k] = sqrt(DCOV[k]);
            else DCOV[k] = 0.0;
    }
    /* compute dCor(x, y) */
    V = DCOV[2]*DCOV[3];
    if (V > DBL_EPSILON)
        DCOV[1] = DCOV[0] / sqrt(V);
        else DCOV[1] = 0.0;

    free_matrix(A, n, n);
    free_matrix(B, n, n);
    return;
}
예제 #5
0
파일: dcov.c 프로젝트: xiangdiuxiu/CodeShop
void dCOVtest(double *x, double *y, int *byrow, int *dims,
              double *index, double *reps,
              double *DCOV, double *pval) {
    /*  computes dCov(x,y), dCor(x,y), dVar(x), dVar(y)
        V-statistic is n*dCov^2 where n*dCov^2 --> Q
        dims[0] = n (sample size)
        dims[1] = p (dimension of X)
        dims[2] = q (dimension of Y)
        dims[3] = dst (logical, TRUE if x, y are distances)
        dims[4] = R (number of replicates)
        index : exponent for distance
        DCOV  : vector [dCov, dCor, dVar(x), dVar(y), mean(A), mean(B)]
     */
    int    i, j, k, n, n2, p, q, r, J, K, M, R;
    int    dst;
    int*   perm;
    double **Dx, **Dy, **A, **B;
    double dcov, V;

    n = dims[0];
    p = dims[1];
    q = dims[2];
    dst = dims[3];
    R = dims[4];

    if (*byrow == FALSE) {
        /* avoid this step: use as.double(t(x)) in R */
        roworder(x, byrow, n, p);
        *byrow = FALSE;  /* false for y */
        roworder(y, byrow, n, q);
    }

    /* critical to pass correct flag dst from R */
    Dx = alloc_matrix(n, n);
    Dy = alloc_matrix(n, n);
    if (dst) {
		vector2matrix(x, Dx, n, n, 1);
		vector2matrix(y, Dy, n, n, 1);
	}
	else {
		Euclidean_distance(x, Dx, n, p);
		Euclidean_distance(y, Dy, n, q);
	}
	index_distance(Dx, n, *index);
	index_distance(Dy, n, *index);

    A = alloc_matrix(n, n);
    B = alloc_matrix(n, n);
    Akl(Dx, A, n);
    Akl(Dy, B, n);
    free_matrix(Dx, n, n);
    free_matrix(Dy, n, n);

    n2 = ((double) n) * n;

    /* compute dCov(x,y), dVar(x), dVar(y) */
    for (k=0; k<4; k++)
        DCOV[k] = 0.0;
    for (k=0; k<n; k++)
        for (j=0; j<n; j++) {
            DCOV[0] += A[k][j]*B[k][j];
            DCOV[2] += A[k][j]*A[k][j];
            DCOV[3] += B[k][j]*B[k][j];
        }

    for (k=0; k<4; k++) {
        DCOV[k] /= n2;
        if (DCOV[k] > 0)
            DCOV[k] = sqrt(DCOV[k]);
            else DCOV[k] = 0.0;
    }
    /* compute dCor(x, y) */
    V = DCOV[2]*DCOV[3];
    if (V > DBL_EPSILON)
        DCOV[1] = DCOV[0] / sqrt(V);
        else DCOV[1] = 0.0;

	if (R > 0) {
		/* compute the replicates */
		if (DCOV[1] > 0.0) {
			perm = Calloc(n, int);
			M = 0;
			for (i=0; i<n; i++) perm[i] = i;
			for (r=0; r<R; r++) {
			   permute(perm, n);
			   dcov = 0.0;
			   for (k=0; k<n; k++) {
				   K = perm[k];
				   for (j=0; j<n; j++) {
					   J = perm[j];
					   dcov += A[k][j]*B[K][J];
				   }
			   }
			   dcov /= n2;
			   dcov = sqrt(dcov);
			   reps[r] = dcov;
			   if (dcov >= DCOV[0]) M++;
			}
			*pval = (double) (M+1) / (double) (R+1);
			Free(perm);
		} else {
/************************************************************************************************************************************
void update_yuv(unsigned char** Y, unsigned char** U, unsigned char** V, int height, int width)
{
	FILE* fp;
	int outer_r, inner_r, outer_c, inner_c;

	if((fp = fopen("Down_Sampled_YUV","rb")) == NULL)
	{
		printf("\n In update_yuv() Error opening DCT_output file !");
		exit(0);
	}

	for(outer_r =0; outer_r < height; outer_r += 8)
	{
		for(outer_c = 0; outer_c < width; outer_c += 8)
		{
			for(inner_r = outer_r; inner_r < outer_r+8; inner_r++)
			{
				for(inner_c = outer_c; inner_c < outer_c+8; inner_c++)
				{
					fscanf(fp,"%d\t",Y[inner_r][inner_c]);
				}
			}
		}
	}

	for(outer_r =0; outer_r < height; outer_r += 8)
	{
		for(outer_c = 0; outer_c < width; outer_c += 8)
		{
			for(inner_r = outer_r; inner_r < outer_r+8; inner_r++)
			{
				for(inner_c = outer_c; inner_c < outer_c+8; inner_c++)
				{
					fscanf(fp,"%d\t",U[inner_r][inner_c]);
				}
			}
		}
	}

	for(outer_r =0; outer_r < height; outer_r += 8)
	{
		for(outer_c = 0; outer_c < width; outer_c += 8)
		{
			for(inner_r = outer_r; inner_r < outer_r+8; inner_r++)
			{
				for(inner_c = outer_c; inner_c < outer_c+8; inner_c++)
				{
					fscanf(fp,"%d\t",V[inner_r][inner_c]);
				}
			}
		}
	}

}

***************************************************************************************************************************************/
  int main(int argc, char const *argv[])
   {
	FILE*fp, *image_rgb, *image_yuv, *down_sampled, *DCT, *image;
	unsigned char** red, **green, **blue, **Y, **U, **V, *image_contents_rgb, *image_contents_yuv, *image_contents_rgbt;
	int i,ERROR;
	Header1 header1;
	Header2 header2;
	
	if((image_rgb = fopen("Image_Contents_RGB","wb")) == NULL)	/*For storing RGB contents*/
	{
		printf("\n Error creating Image_Contents_RGB file !!");
		return -1;
	}
	
	if((image_yuv = fopen("Image_Contents_YUV","wb")) == NULL)	/* For storing YUV contents*/
	{
		printf("\n Error creating Image_Contents_YUV file !!");
		return -1;
	}

	if((down_sampled = fopen("Down_Sampled_YUV","wb")) == NULL)	/* For storing down sampled YUV contents*/
	{
		printf("\n Error creating Down_Sampled_YUV file !!");
		return -1;
	}

	if((DCT = fopen("DCT_Output","wb")) == NULL)				/* For storing DCT contents*/
	{
		printf("\n Error creating Down_Sampled_YUV file !!");
		return -1;
	}	

	if(argc!= 2)												/* syntax error check*/
	{
		printf("\n The format is ./quantizer [file-name]");
		return -1;
	}

	if((fp = fopen(argv[1],"rb"))== NULL) 						/* open the .bmp file for reading*/
	{
		printf("\n Error opening the file specified. Please check if the file exists !!\n");
		fclose(fp);
		return -1;
	}

	if(fread(&header1,sizeof(header1),1,fp)!=1) 				/* Read the primary header from the bmp file */
	{
		printf("\n Error reading header1 \n");
		fclose(fp);
		return -1;
	}

	if(header1.type!= 19778)									/* check if its a valid bmp file*/
	{
		printf("\n Not a bmp file. Exiting !! \n");
		fclose(fp);
		return -1;
	}

	if(fread(&header2,sizeof(header2),1,fp)!=1 )
	{
		printf("\n Error reading header 2");
		fclose(fp);
		return -1;
	} 

	image_contents_rgb = (unsigned char*)malloc(sizeof(char) * header2.imagesize); 
	image_contents_rgbt = (unsigned char*)malloc(sizeof(char) * header2.imagesize);	/*allocate memory to store image data*/
	image_contents_yuv = (unsigned char*)malloc(sizeof(char) * header2.imagesize);

	fseek(fp,header1.offset,SEEK_SET); 												/* To assign file pointer to start of image byte*/ 	

	if((ERROR = fread(image_contents_rgb,header2.imagesize,1,fp))!=1)
	{
		printf("\nError reading contents\n");
		free(image_contents_rgb);
		fclose(fp);
		return -1;
	} 

	fclose(fp);

	red = (unsigned char**)malloc(sizeof(char*) * header2.height);
	green = (unsigned char**)malloc(sizeof(char*) * header2.height);
	blue = (unsigned char**)malloc(sizeof(char*) * header2.height);
	Y = (unsigned char**)malloc(sizeof(char*) * header2.height);
	U = (unsigned char**)malloc(sizeof(char*) * header2.height);
	V = (unsigned char**)malloc(sizeof(char*) * header2.height);

	for(i=0 ; i<header2.height ;i++)
	{
		red[i] = (unsigned char*)malloc( sizeof(char) * header2.width);
		green[i]= (unsigned char*)malloc( sizeof(char) * header2.width);
		blue[i]= (unsigned char*)malloc( sizeof(char) * header2.width);
		Y[i] = (unsigned char*)malloc( sizeof(char) * header2.width);
		U[i] = (unsigned char*)malloc( sizeof(char) * header2.width);
		V[i] = (unsigned char*)malloc( sizeof(char) * header2.width);
	}	
	
	vector2matrix(red, green, blue, image_contents_rgb, header2.height, header2.width); 	/* Store image contents as matrix */
	FileWrite(red, green, blue, image_rgb, header2.height, header2.width);					/* Optional step*/
	rgb2yuv(red,green,blue,Y,U,V,header2.height,header2.width);								/* RGB to YUV conversion*/
	FileWrite(Y, U, V, image_yuv, header2.height, header2.width);							/* Writing YUV into file*/			
	downsampling(Y, U, V, header2.height, header2.width);									/* 4:2:0 Downsampling and update YUV */ 
	FileWrite(Y, U, V, down_sampled, header2.height, header2.width);						/* Write downsampled YUV into file*/
	dct(DCT, header2.height, header2.width);												/* Perform dct and store the result into a file*/
	printf("\n");
	
	yuv2rgb(red,green,blue,Y,U,V,header2.height,header2.width);								/* Optional step*/
	matrix2vector_rgb(red,green,blue,image_contents_rgbt,header2.height,header2.width); 	/* convert back from matrix to vector*/
	matrix2vector_yuv(Y,U,V,image_contents_yuv,header2.height,header2.width);

	if((image = fopen("Output_image","wb")) == NULL)
	{
		printf("\n ERROR opening the file to write quantized image !!\n");
		fclose(image);
		return -1;
	}

	if(fwrite(&header1,sizeof(header1),1,image)!= 1)
	{
		printf("\n ERROR writing header 1 into destination file !!\n");
		fclose(image);
		return -1;
	}

	if(fwrite(&header2,sizeof(header2),1,image)!= 1)
	{
		printf("\n ERROR writing header 2 into destination file !! \n");
		fclose(image);
		return -1;
	}

	fseek(image, header1.offset, SEEK_SET);

	if(fwrite(image_contents_rgbt,header2.imagesize,1,image)!=1)		/* Change the vector to write into the bmp file here*/
	{
		printf("\n ERROR writing image contents into destination file \n");
		fclose(image);
		return -1;
	}

	free(red);
	free(green);
	free(blue);
	free(Y);
	free(U);
	free(V);
	fclose(image);
	return 0;
}
int main(int argc, char const *argv[])
{
	FILE*fp,*image;
	unsigned char** red,**green,**blue,**Y,**U,**V,*image_contents_rgb, *image_contents_yuv, *image_contents_rgbt;
	int i,j,x,y,row_index, col_index,ERROR;
	Header1 header1;
	Header2 header2;
	/* -----------------------------				Task 1			-------------------------------------- */
	 int array[8][8] = {{48,39,40,68,60,38,50,121},
	{149,82,79,101,113,106,27,62},
	{58,63,77,69,124,107,74,125},
	{80,97,74,54,59,71,91,66},
	{18,34,33,46,64,61,32,37},
	{149,108,80,106,116,61,73,92},
	{211,233,159,88,107,158,161,109},
	{212,104,40,44,71,136,113,66}};
	printf("\n\n *************************** Activity 1: SAMPLE BLOCK *************** \n");
	dct(array);
	/*----------------------------					Task2 			----------------------------------------- */
	srand(time(NULL));
	printf("\n\n *************************** Activity 2: RANDOM BLOCK **************** \n\n");
	for(i =0; i<block_size; ++i)
	{
		for(j=0; j<block_size; ++j)
		{
			array[i][j] = rand()%150;
		}
	}
	dct(array);
	printf("\n");
	/*------------------------------			Task3 				------------------------------------------- */
	if(argc!= 2)																/* syntax error check*/
	{
		printf("\n The format is ./quantizer [file-name]");
		return -1;
	}

	if((fp = fopen(argv[1],"rb"))== NULL) 										/* open the .bmp file for reading*/
	{
		printf("\n Error opening the file specified. Please check if the file exists !!\n");
		fclose(fp);
		return -1;
	}

	if(fread(&header1,sizeof(header1),1,fp)!=1) 								/* Read the primary header from the bmp file */
	{
		printf("\n Error reading header1 \n");
		fclose(fp);
		return -1;
	}

	if(header1.type!= 19778)													/* check if its a valid bmp file*/
	{
		printf("\n Not a bmp file. Exiting !! \n");
		fclose(fp);
		return -1;
	}

	if(fread(&header2,sizeof(header2),1,fp)!=1 )
	{
		printf("\n Error reading header 2");
		fclose(fp);
		return -1;
	} 

	image_contents_rgb = (unsigned char*)malloc(sizeof(char) * header2.imagesize); 
	image_contents_rgbt = (unsigned char*)malloc(sizeof(char) * header2.imagesize);	/*allocate memory to store image data*/
	image_contents_yuv = (unsigned char*)malloc(sizeof(char) * header2.imagesize);

	fseek(fp,header1.offset,SEEK_SET); 	

	if((ERROR=fread(image_contents_rgb,header2.imagesize,1,fp))!=1)
	{
		printf("\nError reading contents\n");
		free(image_contents_rgb);
		fclose(fp);
		return -1;
	} 

	fclose(fp);

	red = (unsigned char**)malloc(sizeof(char*) * header2.height);
	green = (unsigned char**)malloc(sizeof(char*) * header2.height);
	blue = (unsigned char**)malloc(sizeof(char*) * header2.height);
	Y = (unsigned char**)malloc(sizeof(char*) * header2.height);
	U = (unsigned char**)malloc(sizeof(char*) * header2.height);
	V = (unsigned char**)malloc(sizeof(char*) * header2.height);

	for(i=0 ; i<header2.height ;i++)
	{
		red[i] = (unsigned char*)malloc( sizeof(char) * header2.width);
		green[i]= (unsigned char*)malloc( sizeof(char) * header2.width);
		blue[i]= (unsigned char*)malloc( sizeof(char) * header2.width);
		Y[i] = (unsigned char*)malloc( sizeof(char) * header2.width);
		U[i] = (unsigned char*)malloc( sizeof(char) * header2.width);
		V[i] = (unsigned char*)malloc( sizeof(char) * header2.width);
	}	
	
	vector2matrix(red,green,blue,image_contents_rgb,header2.height,header2.width); 		/* call to store image contents as matrix */
	printf("\n\n *********************** Activity 3: RGB Image Block *********************\n");
	printf(" Enter the starting row index and coloumn index respectively: ");
	scanf("%d %d",&row_index,&col_index);
	for(i = 0, x = row_index; i < block_size && x<row_index+8; ++i, ++x)
	{
		for(j= 0, y = col_index; j < block_size && y<col_index+8; ++j, ++y)
		{
			if(x<512 && y<512)
				array[i][j] = blue[x][y];
			else
				array[i][j] = 0;
		}
	}
	dct(array);
	rgb2yuv(red,green,blue,Y,U,V,header2.height,header2.width);								/* Downsampling*/
	printf("\n\n *********************** Activity 4: YUV Image Block *********************\n");
	printf(" Enter the starting row index and coloumn index respectively: ");
	scanf("%d %d",&row_index,&col_index);
	for(i = 0, x = row_index; i < block_size && x<row_index+8; ++i, ++x)
	{
		for(j= 0, y = col_index; j < block_size && y<col_index+8; ++j, ++y)
		{
			if(x<512 && y<512)
				array[i][j] = V[x][y];
			else
				array[i][j] = 0;
		}
	}
	dct(array);
	yuv2rgb(red,green,blue,Y,U,V,header2.height,header2.width);							/* convert back to RGB*/									
	matrix2vector_rgb(red,green,blue,image_contents_rgbt,header2.height,header2.width); /* convert back from matrix to vector*/
	matrix2vector_yuv(Y,U,V,image_contents_yuv,header2.height,header2.width);

	if((image = fopen("Output_image","wb")) == NULL)
	{
		printf("\n ERROR opening the file to write quantized image !!\n");
		fclose(image);
		return -1;
	}

	if(fwrite(&header1,sizeof(header1),1,image)!= 1)
	{
		printf("\n ERROR writing header 1 into destination file !!\n");
		fclose(image);
		return -1;
	}

	if(fwrite(&header2,sizeof(header2),1,image)!= 1)
	{
		printf("\n ERROR writing header 2 into destination file !! \n");
		fclose(image);
		return -1;
	}

	fseek(image, header1.offset, SEEK_SET);

	if(fwrite(image_contents_rgbt,header2.imagesize,1,image)!=1)					/* Change the vector to write into the bmp file here*/
	{
		printf("\n ERROR writing image contents into destination file \n");
		fclose(image);
		return -1;
	}

	free(red);
	free(green);
	free(blue);
	free(Y);
	free(U);
	free(V);
	free(image_contents_rgb);
	free(image_contents_yuv);
	fclose(image);
	return 0;
}