01: #include<stdio.h>
02: #include<stdlib.h>
03: #include<string.h>
04: 
05: int *load_pgm(char *filename, int *sizex, int *sizey)
06: {
07:   int colors;
08:   char intestaz[1000];   // if the file is a PGM 3 bytes are enough. In order to check if the file is actually a PGM, it is better to allocate an insanely large buffer
09:   FILE *fin;
10:   int *dati;
11: 
12:   fin=fopen(filename, "r");
13:   if(!fin)
14:   {
15:     perror(filename);
16:     exit(EXIT_FAILURE);
17:   }
18: 
19:   fscanf(fin, "%s", intestaz); // read file format header
20:   if(strcmp(intestaz, "P2"))
21:   {
22:     printf("Errore, file non supportato!\n");
23:     exit(EXIT_FAILURE);
24:   }
25: 
26:   fscanf(fin, "%d %d %d", sizex, sizey, &colors); // read image size and maximum color numbers
27:   //printf("DEBUG: ho letto %d %d con %d colori\n", *sizex, *sizey, colors);
28: 
29:   dati = malloc((*sizex)*(*sizey)*sizeof(int)); // allocate space for image data
30:   if(!dati)
31:   {
32:     printf("Errore, in allocazione di %ld byte\n", *sizex**sizey*sizeof(int));
33:     exit(EXIT_FAILURE);
34:   }
35: 
36:   for(int i=0; i < (*sizex)*(*sizey); ++i)
37:     fscanf(fin, "%d", &dati[i]); // assuming file is not corrupted!
38: 
39:   fclose(fin);
40:   return dati;
41: }
42: 
43: int *vedge(const int *dati, int cols, int rows, int th)
44: {
45: 
46:   int *copy = malloc(rows*cols*sizeof(int));
47: 
48:     for(int i=1; i < (cols*rows-1); ++i)
49:     {
50:       copy[i] = abs(dati[i - 1] - dati[i + 1]);
51:       if(copy[i] <= th)
52:   copy[i] = 0;
53:     }
54: 
55:   return copy;
56: }
57: 
58: 
59: void save_pgm(const char *filename, const int *dati, int cols, int rows)
60: {
61:   FILE *fout;
62:   fout = fopen(filename, "w");
63:   if(!fout)
64:   {
65:     perror(filename);
66:     exit(EXIT_FAILURE);
67:   }
68: 
69:   fprintf(fout, "P2\n");
70:   fprintf(fout, "%d %d\n", cols, rows);
71:   fprintf(fout, "255\n");
72: 
73:   for(int i=0; i<cols*rows; ++i)
74:   {
75:     fprintf(fout, "%d ", dati[i]);
76:   }
77: 
78:   fclose(fout);
79: }
80: 
81: int main(int argc, char **argv){
82: 
83:   int *img, cols, rows;
84: 
85:   img = load_pgm("sample.pgm", &cols, &rows);
86:   int *filtered = vedge(img, cols, rows, 20);
87:   save_pgm("out.pgm", filtered, cols, rows);
88: 
89:   return 0;
90: }
91: 
92: