Grabbing Pixels from PGM Image using C
By admin on March 24th, 2009
#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 PGM\n");
}
//Check the Commnets
fgets(header, 100, fp);
while (header[0] == '#') {
//printf("%c\n", header[0]);
fgets(header, 100, fp);
}
//Get Width and Height
width = strtol(header, &amp; ptr, 0);
height = atoi(ptr);
// Get Maximum Gray Value
fgets(header, 100, fp);
q = strtol(header, &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 & 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 & lt; height; i++) {
for (j = 0; j & 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 & lt; height; i++) {
for (j = 0; j & lt; width; j++) {
charImage[i * width + j] = pels[i][j];
}
}
fprintf(fp1, "P5\n%d\n%d\n255\n", width, height);
fwrite(charImage, 1, width*height, fp1);
fclose(fp1);
}
int main() {
int** p = imageRead("sam1.pgm");
imageWrite(p);
return 0;
}
Leave a Response
For this kind of blog post we need a fixed width font or else the alignment get disturbed. double column template would be most appropriate and a small description would help a lot here. Without a small appropriated description no one can get to this blog post easily from a google search. A small input/output sample would go even further to make it usable.
Regards.