-
Notifications
You must be signed in to change notification settings - Fork 0
/
image.cu
121 lines (95 loc) · 2.76 KB
/
image.cu
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include "image.cuh"
void PnmImage::read(const char *fileName) {
if (pixels)
free(pixels);
FILE *f = fopen(fileName, "r");
if (f == nullptr) {
printf("Cannot read %s\n", fileName);
exit(EXIT_FAILURE);
}
char type[3];
fscanf(f, "%s", type);
if (strcmp(type, "P3") != 0) // In this exercise, we don't touch other types
{
fclose(f);
printf("Cannot read %s\n", fileName);
exit(EXIT_FAILURE);
}
fscanf(f, "%i", &width);
fscanf(f, "%i", &height);
int max_val;
fscanf(f, "%i", &max_val);
if (max_val > 255) // In this exercise, we assume 1 byte per value
{
fclose(f);
printf("Cannot read %s\n", fileName);
exit(EXIT_FAILURE);
}
pixels = (uchar3 *) malloc(width * height * sizeof(uchar3));
for (int i = 0; i < width * height; i++)
fscanf(f, "%hhu%hhu%hhu", &pixels[i].x, &pixels[i].y, &pixels[i].z);
fclose(f);
}
void PnmImage::write(const char *fileName) {
FILE *f = fopen(fileName, "w");
if (f == nullptr) {
printf("Cannot write %s\n", fileName);
exit(EXIT_FAILURE);
}
fprintf(f, "P3\n%i\n%i\n255\n", width, height);
for (int i = 0; i < width * height; i++)
fprintf(f, "%hhu\n%hhu\n%hhu\n", pixels[i].x, pixels[i].y, pixels[i].z);
fclose(f);
}
void PnmImage::compare(const PnmImage &other) {
float err = 0;
if (this->height != other.height || this->width != other.width)
err = -1;
else
err = computeError(this->pixels, other.pixels, width * height);
printf("Error: %f\n", err);
}
long long PnmImage::sum(){
long long res = 0;
for(int i = 0; i < this->height; i++)
for(int j = 0; j < this->width; j++){
uchar3 pixel = pixels[i * this->width + j];
res += pixel.x + pixel.y + pixel.z;
}
return res;
}
float PnmImage::computeError(uchar3 *a1, uchar3 *a2, uint32_t n) {
long long err = 0;
for (int i = 0; i < n; i++) {
err += abs((int) a1[i].x - (int) a2[i].x);
err += abs((int) a1[i].y - (int) a2[i].y);
err += abs((int) a1[i].z - (int) a2[i].z);
}
return float(double(err) / double(n * 3));
}
uint32_t PnmImage::getWidth() const {
return width;
}
uint32_t PnmImage::getHeight() const {
return height;
}
uchar3 *PnmImage::getPixels() const {
return pixels;
}
uint32_t IntImage::getWidth() const {
return width;
}
uint32_t IntImage::getHeight() const {
return height;
}
int32_t *IntImage::getPixels() const {
return pixels;
}
long long IntImage::sum(){
long long res = 0;
for(int i = 0; i < this->height; i++)
for(int j = 0; j < this->width; j++){
res += pixels[i * this->width + j];
}
return res;
}