Debian Codegraph @

src/SPERR/utilities/raw_tools/crop_2d.c

raw
1 /*
2 This program reads in a 2D binary raw file of dimension (IN_NX, IN_NY),
3 crops the corner with dimension (OUT_NX, OUT_NY), and outputs the corner.
4 */
5 #include <stdio.h>
6 #include <stdlib.h>
7
8 #define IN_NX 128
9 #define IN_NY 128
10 #define OUT_NX 15
11 #define OUT_NY 15
12
13 int main(int argc, char** argv)
14 {
15 if (argc != 3) {
16 fprintf(stderr, "Usage: ./a.out input_filename output_filename.\n");
17 return 1;
18 }
19
20 const long in_num_of_vals = IN_NX * IN_NY;
21 const long in_num_of_bytes = in_num_of_vals * sizeof(float);
22 const long out_num_of_vals = OUT_NX * OUT_NY;
23 const long out_num_of_bytes = out_num_of_vals * sizeof(float);
24
25 /* Check if the file to read is good */
26 FILE* f = fopen(argv[1], "r");
27 if (f == NULL) {
28 fprintf(stderr, "Error! Cannot open input file: %s\n", argv[1]);
29 return 1;
30 }
31 fseek(f, 0, SEEK_END);
32 if (ftell(f) != in_num_of_bytes) {
33 fprintf(stderr, "Error! Input file size error: %s\n", argv[1]);
34 fprintf(stderr, " Expecting %ld bytes, got %ld bytes.\n", in_num_of_bytes, ftell(f));
35 fclose(f);
36 return 1;
37 }
38 fseek(f, 0, SEEK_SET);
39
40 /* Allocate space for the input data */
41 float* in_buf = (float*)malloc(in_num_of_bytes);
42 if (fread(in_buf, sizeof(float), in_num_of_vals, f) != in_num_of_vals) {
43 fprintf(stderr, "Error! Input file read error: %s\n", argv[1]);
44 free(in_buf);
45 fclose(f);
46 return 1;
47 }
48 fclose(f);
49
50 /* Allocate space for the output data, and fill it up. */
51 float* out_buf = (float*)malloc(out_num_of_bytes);
52 long x, y, counter = 0;
53 for (y = 0; y < OUT_NY; y++)
54 for (x = 0; x < OUT_NX; x++) {
55 long in_idx = y * IN_NX + x;
56 out_buf[counter++] = in_buf[in_idx];
57 }
58
59 /* Write out_buf to a file. */
60 f = fopen(argv[2], "w");
61 if (f == NULL) {
62 fprintf(stderr, "Error! Cannot open output file: %s\n", argv[2]);
63 free(in_buf);
64 free(out_buf);
65 return 1;
66 }
67 if (fwrite(out_buf, sizeof(float), out_num_of_vals, f) != out_num_of_vals) {
68 fprintf(stderr, "Error! Input file write error: %s\n", argv[2]);
69 free(in_buf);
70 free(out_buf);
71 fclose(f);
72 return 1;
73 }
74 fclose(f);
75 free(in_buf);
76 free(out_buf);
77
78 printf("*** SUCCESS cropping %s to %s! ***\n", argv[1], argv[2]);
79 return 0;
80 }