-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhistogram.cpp
More file actions
94 lines (76 loc) · 2.04 KB
/
Copy pathhistogram.cpp
File metadata and controls
94 lines (76 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <cassert>
#include "Timer.h"
extern "C" {
#include "ppmb_io.h"
}
struct img {
int xsize;
int ysize;
int maxrgb;
unsigned char *r;
unsigned char *g;
unsigned char *b;
};
void print_histogram(FILE *f, int *hist, int N) {
fprintf(f, "%d\n", N+1);
for(int i = 0; i <= N; i++) {
fprintf(f, "%d %d\n", i, hist[i]);
}
}
void histogram(struct img *input, int *hist_r, int *hist_g, int *hist_b) {
// we assume hist_r, hist_g, hist_b are zeroed on entry.
for(int pix = 0; pix < input->xsize * input->ysize; pix++) {
hist_r[input->r[pix]] += 1;
hist_g[input->g[pix]] += 1;
hist_b[input->b[pix]] += 1;
}
}
char *get_output_file(const char *input) {
char *out;
out = (char *) malloc(strlen(input) + strlen(".hist") + 1);
if(!out) {
fprintf(stderr, "Unable to allocate memory\n");
exit(1);
}
if(sprintf(out, "%s.hist", input) < 0) {
fprintf(stderr, "sprintf error\n");
exit(1);
}
return out;
}
int main(int argc, char *argv[]) {
if(argc != 2) {
printf("Usage: %s input-file\n", argv[0]);
exit(1);
}
struct img input;
if(!ppmb_read(argv[1], &input.xsize, &input.ysize, &input.maxrgb,
&input.r, &input.g, &input.b)) {
if(input.maxrgb > 255) {
printf("Maxrgb %d not supported\n", input.maxrgb);
exit(1);
}
int *hist_r, *hist_g, *hist_b;
hist_r = (int *) calloc(input.maxrgb+1, sizeof(int));
hist_g = (int *) calloc(input.maxrgb+1, sizeof(int));
hist_b = (int *) calloc(input.maxrgb+1, sizeof(int));
ggc::Timer t("histogram");
t.start();
histogram(&input, hist_r, hist_g, hist_b);
t.stop();
char *output = get_output_file(argv[1]);
FILE *out = fopen(output, "w");
if(out) {
print_histogram(out, hist_r, input.maxrgb);
print_histogram(out, hist_g, input.maxrgb);
print_histogram(out, hist_b, input.maxrgb);
fclose(out);
} else {
fprintf(stderr, "Unable to output!\n");
}
printf("Time: %llu ns\n", t.duration());
}
}