-
Notifications
You must be signed in to change notification settings - Fork 0
/
omp_imp2.c
135 lines (130 loc) · 3.2 KB
/
omp_imp2.c
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <omp.h>
#include <math.h>
#include <sys/time.h>
int N;
int P;
int width, height;
int maxval;
int size;
unsigned char *img;
unsigned char *img_new;
void read_image(char *name)
{
FILE *f = fopen(name, "r");
char *aux = malloc(2);
if (!aux)
return;
fscanf(f, "%s\n", aux);
P = aux[1] - 48;
aux = realloc(aux, 500);
fgets(aux, 500, f);
fscanf(f, "%d %d\n", &width, &height);
fscanf(f, "%d\n", &maxval);
free(aux);
if (P == 5)
{
size = width * height;
}
else if (P == 6)
{
size = width * height * 3;
}
img = malloc(size);
if (!img)
{
return;
}
for (int i = 0; i < size; ++i)
{
fscanf(f, "%c", &img[i]);
}
}
void edit_image()
{
if (P == 5)
{
#pragma omp parallel for
for (int i = 1; i < height - 1; ++i)
{
for (int j = 1; j < width - 1; ++j)
{
unsigned char min_val = 255;
for (int a = -1; a <= 1; ++a)
{
for (int b = -1; b <= 1; ++b)
{
if (img[(i + a) * width + j + b] < min_val)
min_val = img[(i + a) * width + j + b];
}
}
img_new[i * width + j] = min_val;
}
}
}
else if (P == 6)
{
#pragma omp parallel for
for (int i = 1; i < height - 1; i++)
{
for (int j = 3; j < 3 * width - 3; j += 3)
{
for (int t = 0; t < 3; ++t)
{
unsigned char min_val = 255;
for (int a = -1; a <= 1; ++a)
{
for (int b = -3; b <= 3; b += 3)
{
if (img[(i + a) * 3 * width + j + b + t] < min_val)
min_val = img[(i + a) * 3 * width + j + b + t];
}
}
img_new[i * 3 * width + j + t] = min_val;
}
}
}
}
}
void write_image(char *name)
{
FILE *f = fopen(name, "w");
fprintf(f, "P%d\n", P);
fprintf(f, "%d %d\n", width, height);
fprintf(f, "%d\n", maxval);
for (int i = 0; i < size; ++i)
{
fprintf(f, "%c", img_new[i]);
}
}
int main(int argc, char const *argv[])
{
struct timeval start_time, end_time;
double elapsed;
if (argc != 4)
{
printf("Not enough arguments! Usage: ./openmp2 file_in_name file_out_name num_threads\n");
return -1;
}
char *name_in = strdup(argv[1]);
char *name_out = strdup(argv[2]);
N = atoi(argv[3]);
read_image(name_in);
img_new = malloc(size);
if (!img_new)
{
return -1;
}
gettimeofday(&start_time, 0);
omp_set_num_threads(N);
edit_image();
gettimeofday(&end_time, 0);
long seconds = end_time.tv_sec - start_time.tv_sec;
long microseconds = end_time.tv_usec - start_time.tv_usec;
elapsed = seconds + microseconds * 1e-6;
printf("\nOMP2 took %f seconds with %d threads\n", elapsed, N);
write_image(name_out);
return 0;
}