Grabbing Pixels from PGM Image using C


#include<stdio.h>
#include<string.h>
#include<stdlib.h>
/*
* Auhtor : Anthoniraj.A
* Date : 24/03/2009
*/
int** imageRead(char imageName[]);
void imageWrite(int** pels);
int width, height;
int **pixels;
unsigned char *charImage;
 
int** imageRead(char imageName[]) {
FILE* fp;
 
//PGM Headers Variable Declaration
char* type;
int *ptr;
int q, i, j;
 
char header[100];
//Open file for Reading in Binary Mode
//fp = fopen("/home/anthoniraj/image.pgm","rb");
fp = fopen(imageName, "rb");
if (fp == NULL) {
printf("Image does not exist n");
} else {
//Check the PGM file Type P2 or P5
fgets(header, 100, fp);
if ((header[0] != 80) || (header[1] != 53)) {
printf("Image is not PGMn");
 
}
 
//Check the Commnets
fgets(header, 100, fp);
while (header[0] == '#') {
//printf("%cn", header[0]);
fgets(header, 100, fp);
}
 
//Get Width and Height
width = strtol(header, &amp;amp; ptr, 0);
height = atoi(ptr);
 
// Get Maximum Gray Value
fgets(header, 100, fp);
q = strtol(header, &amp;amp; ptr, 0);
 
//Allocating Array Size
charImage = (unsigned char*) malloc(width * height * sizeof (unsigned char));
pixels = (int **) malloc(width * sizeof (int *));
for (i = 0; i &amp; lt; height; i++)
pixels[i] = (int *) malloc(height * sizeof (int));
 
// Pixel Extraction
fread(charImage, 1, (width * height) * sizeof (unsigned char), fp);
for (i = 0; i &amp; lt; height; i++) {
for (j = 0; j &amp; lt; width; j++) {
pixels[i][j] = (int) charImage[i * width + j];
// printf("%d ",pixels[i][j]);
}
//printf("n");
}
 
// Pixel Extraction
fclose(fp);
}
return pixels;
}
 
void imageWrite(int** pels) {
int i, j;
FILE* fp1;
fp1 = fopen("out.pgm", "w");
 
for (i = 0; i &amp; lt; height; i++) {
for (j = 0; j &amp; lt; width; j++) {
charImage[i * width + j] = pels[i][j];
}
}
fprintf(fp1, "P5n%dn%dn255n", width, height);
fwrite(charImage, 1, width*height, fp1);
fclose(fp1);
}
 
int main() {
int** p = imageRead("sam1.pgm");
imageWrite(p);
return 0;
}

No comments:

Post a Comment