-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenMP
More file actions
506 lines (442 loc) · 19.2 KB
/
Copy pathOpenMP
File metadata and controls
506 lines (442 loc) · 19.2 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
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
//
// convolution.c
//
//
// Created by Josep Lluis Lerida on 11/03/15.
//
// This program calculates the convolution for PPM images.
// The program accepts an PPM image file, a text definition of the kernel matrix and the PPM file for storing the convolution results.
// The program allows to define image partitions for processing large images (>500MB)
// The 2D image is represented by 1D vector for chanel R, G and B. The convolution is applied to each chanel separately.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <omp.h>
// Estructura per emmagatzemar el contingut d'una imatge.
struct imagenppm{
int altura;
int ancho;
char *comentario;
int maxcolor;
int P;
int *R;
int *G;
int *B;
};
typedef struct imagenppm* ImagenData;
// Estructura per emmagatzemar el contingut d'un kernel.
struct structkernel{
int kernelX;
int kernelY;
float *vkern;
};
typedef struct structkernel* kernelData;
//Functions Definition
ImagenData initimage(char* nombre, FILE **fp, int partitions, int halo);
ImagenData duplicateImageData(ImagenData src, int partitions, int halo);
int readImage(ImagenData Img, FILE **fp, int dim, int halosize, long int *position);
int duplicateImageChunk(ImagenData src, ImagenData dst, int dim);
int initfilestore(ImagenData img, FILE **fp, char* nombre, long *position);
int savingChunk(ImagenData img, FILE **fp, int dim, int offset);
int convolve2D(int* inbuf, int* outbuf, int sizeX, int sizeY, float* kernel, int ksizeX, int ksizeY);
void freeImagestructure(ImagenData *src);
//Open Image file and image struct initialization
ImagenData initimage(char* nombre, FILE **fp,int partitions, int halo){
char c;
char comentario[300];
int i=0,chunk=0;
ImagenData img=NULL;
/*Se habre el fichero ppm*/
if ((*fp=fopen(nombre,"r"))==NULL){
perror("Error: ");
}
else{
//Memory allocation
img=(ImagenData) malloc(sizeof(struct imagenppm));
//Reading the first line: Magical Number "P3"
fscanf(*fp,"%c%d ",&c,&(img->P));
//Reading the image comment
while((c=fgetc(*fp))!= '\n'){comentario[i]=c;i++;}
comentario[i]='\0';
//Allocating information for the image comment
img->comentario = calloc(strlen(comentario),sizeof(char));
strcpy(img->comentario,comentario);
//Reading image dimensions and color resolution
fscanf(*fp,"%d %d %d",&img->ancho,&img->altura,&img->maxcolor);
chunk = img->ancho*img->altura / partitions;
//We need to read an extra row.
chunk = chunk + img->ancho * halo;
if ((img->R=calloc(chunk,sizeof(int))) == NULL) {return NULL;}
if ((img->G=calloc(chunk,sizeof(int))) == NULL) {return NULL;}
if ((img->B=calloc(chunk,sizeof(int))) == NULL) {return NULL;}
}
return img;
}
//Duplicate the Image struct for the resulting image
ImagenData duplicateImageData(ImagenData src, int partitions, int halo){
char c;
char comentario[300];
unsigned int imageX, imageY;
int i=0, chunk=0;
//Struct memory allocation
ImagenData dst=(ImagenData) malloc(sizeof(struct imagenppm));
//Copying the magic number
dst->P=src->P;
//Copying the string comment
dst->comentario = calloc(strlen(src->comentario),sizeof(char));
strcpy(dst->comentario,src->comentario);
//Copying image dimensions and color resolution
dst->ancho=src->ancho;
dst->altura=src->altura;
dst->maxcolor=src->maxcolor;
chunk = dst->ancho*dst->altura / partitions;
//We need to read an extra row.
chunk = chunk + src->ancho * halo;
if ((dst->R=calloc(chunk,sizeof(int))) == NULL) {return NULL;}
if ((dst->G=calloc(chunk,sizeof(int))) == NULL) {return NULL;}
if ((dst->B=calloc(chunk,sizeof(int))) == NULL) {return NULL;}
return dst;
}
//Read the corresponding chunk from the source Image
int readImage(ImagenData img, FILE **fp, int dim, int halosize, long *position){
int i=0, k=0,haloposition=0;
if (fseek(*fp,*position,SEEK_SET))
perror("Error: ");
haloposition = dim-(img->ancho*halosize*2);
for(i=0;i<dim;i++) {
// When start reading the halo store the position in the image file
if (halosize != 0 && i == haloposition) *position=ftell(*fp);
fscanf(*fp,"%d %d %d ",&img->R[i],&img->G[i],&img->B[i]);
k++;
}
// printf ("Readed = %d pixels, posicio=%lu\n",k,*position);
return 0;
}
//Duplication of the just readed source chunk to the destiny image struct chunk
int duplicateImageChunk(ImagenData src, ImagenData dst, int dim){
int i=0;
for(i=0;i<dim;i++){
dst->R[i] = src->R[i];
dst->G[i] = src->G[i];
dst->B[i] = src->B[i];
}
// printf ("Duplicated = %d pixels\n",i);
return 0;
}
// Open kernel file and reading kernel matrix. The kernel matrix 2D is stored in 1D format.
kernelData leerKernel(char* nombre){
FILE *fp;
int i=0;
kernelData kern=NULL;
/*Opening the kernel file*/
fp=fopen(nombre,"r");
if(!fp){
perror("Error: ");
}
else{
//Memory allocation
kern=(kernelData) malloc(sizeof(struct structkernel));
//Reading kernel matrix dimensions
fscanf(fp,"%d,%d,", &kern->kernelX, &kern->kernelY);
kern->vkern = (float *)malloc(kern->kernelX*kern->kernelY*sizeof(float));
// Reading kernel matrix values
for (i=0;i<(kern->kernelX*kern->kernelY)-1;i++){
fscanf(fp,"%f,",&kern->vkern[i]);
}
fscanf(fp,"%f",&kern->vkern[i]);
fclose(fp);
}
return kern;
}
// Open the image file with the convolution results
int initfilestore(ImagenData img, FILE **fp, char* nombre, long *position){
/*Se crea el fichero con la imagen resultante*/
if ( (*fp=fopen(nombre,"w")) == NULL ){
perror("Error: ");
return -1;
}
/*Writing Image Header*/
fprintf(*fp,"P%d\n%s\n%d %d\n%d\n",img->P,img->comentario,img->ancho,img->altura,img->maxcolor);
*position = ftell(*fp);
return 0;
}
// Writing the image partition to the resulting file. dim is the exact size to write. offset is the displacement for avoid halos.
int savingChunk(ImagenData img, FILE **fp, int dim, int offset){
int i,k=0;
//Writing image partition
for(i=offset;i<dim+offset;i++){
fprintf(*fp,"%d %d %d ",img->R[i],img->G[i],img->B[i]);
// if ((i+1)%6==0) fprintf(*fp,"\n");
k++;
}
// printf ("Writed = %d pixels, dim=%d, offset=%d\n",k,dim, offset);
return 0;
}
// This function free the space allocated for the image structure.
void freeImagestructure(ImagenData *src){
free((*src)->comentario);
free((*src)->R);
free((*src)->G);
free((*src)->B);
free(*src);
}
///////////////////////////////////////////////////////////////////////////////
// 2D convolution
// 2D data are usually stored in computer memory as contiguous 1D array.
// So, we are using 1D array for 2D data.
// 2D convolution assumes the kernel is center originated, which means, if
// kernel size 3 then, k[-1], k[0], k[1]. The middle of index is always 0.
// The following programming logics are somewhat complicated because of using
// pointer indexing in order to minimize the number of multiplications.
//
//
// signed integer (32bit) version:
///////////////////////////////////////////////////////////////////////////////
int convolve2D(int* in, int* out, int dataSizeX, int dataSizeY,
float* kernel, int kernelSizeX, int kernelSizeY)
{
int i, j, m, n, id, Nthrds, ini, fin;
int *inPtr, *inPtr2, *outPtr;
float *kPtr;
int kCenterX, kCenterY;
int rowMin, rowMax; // to check boundary of input array
int colMin, colMax; //
float sum; // temp accumulation buffer
// check validity of params
if(!in || !out || !kernel) return -1;
if(dataSizeX <= 0 || kernelSizeX <= 0) return -1;
// Put the number of threads
omp_set_num_threads(4);
// find center position of kernel (half of kernel size)
kCenterX = (int)kernelSizeX / 2;
kCenterY = (int)kernelSizeY / 2;
//Define the parallel region with the parameters Shared, private and firstprivate. The private variables because each thread need work them as they are declared in the pragma region, and the firstprivate because we need that each thread has the variable with the same value that they have before the pragma
#pragma omp parallel shared(id,Nthrds,dataSizeX,dataSizeY) private(ini,fin,inPtr,inPtr2,outPtr,i,rowMin,rowMax,colMin,colMax,j,m,n,sum) firstprivate(kPtr,kCenterX,kCenterY)
{
// Initialize variables Nthrds, id and fin, in order to calculate the value for each pointer and the variable i for iteration in the rows
Nthrds = omp_get_num_threads();
id = omp_get_thread_num();
ini = id * dataSizeY/Nthrds;
fin = (id+1) * dataSizeY/Nthrds;
if (id == Nthrds-1)
fin = dataSizeY;
//redifine the pointers based on the variable ini for each thread
inPtr = inPtr2 = &in[(ini * dataSizeX) + (dataSizeX * kCenterY + kCenterX)];
outPtr = &out[ini * dataSizeX];
kPtr = kernel;
for(i= ini; i < fin; ++i) // number of rows
{
// compute the range of convolution, the current row of kernel should be between these
// Change the values for rowMax and rowMin
rowMax = i + kCenterY;
rowMin = i - fin + kCenterY;
for(j = 0; j < dataSizeX; ++j) // number of columns
{
// compute the range of convolution, the current column of kernel should be between these
colMax = j + kCenterX;
colMin = j - dataSizeX + kCenterX;
sum = 0; // set to 0 before accumulates
// flip the kernel and traverse all the kernel values
// multiply each kernel value with underlying input data
for(m = 0; m < kernelSizeY; ++m) // kernel rows
{
// check if the index is out of bound of input array
if(m <= rowMax && m > rowMin)
{
for(n = 0; n < kernelSizeX; ++n)
{
// check the boundary of array
if(n <= colMax && n > colMin)
sum += *(inPtr - n) * *kPtr;
++kPtr; // next kernel
}
}
else
kPtr += kernelSizeX; // out of bound, move to next row of kernel
inPtr -= dataSizeX; // move input data 1 raw up
}
// convert integer number
if(sum >= 0) *outPtr = (int)(sum + 0.5f);
// else *outPtr = (int)(sum - 0.5f)*(-1);
// For using with image editors like GIMP or others...
else *outPtr = (int)(sum - 0.5f);
// For using with a text editor that read ppm images like libreoffice or others...
// else *outPtr = 0;
kPtr = kernel; // reset kernel to (0,0)
inPtr = ++inPtr2; // next input
++outPtr; // next output
}
}
}
return 0;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// MAIN FUNCTION
//////////////////////////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
int i=0,j=0,k=0;
// int headstored=0, imagestored=0, stored;
if(argc != 5)
{
printf("Usage: %s <image-file> <kernel-file> <result-file> <partitions>\n", argv[0]);
printf("\n\nError, Missing parameters:\n");
printf("format: ./serialconvolution image_file kernel_file result_file\n");
printf("- image_file : source image path (*.ppm)\n");
printf("- kernel_file: kernel path (text file with 1D kernel matrix)\n");
printf("- result_file: result image path (*.ppm)\n");
printf("- partitions : Image partitions\n\n");
return -1;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// READING IMAGE HEADERS, KERNEL Matrix, DUPLICATE IMAGE DATA, OPEN RESULTING IMAGE FILE
//////////////////////////////////////////////////////////////////////////////////////////////////
int imagesize, partitions, partsize, chunksize, halo, halosize;
long position=0;
double start, tstart=0, tend=0, tread=0, tcopy=0, tconv=0, tstore=0, treadk=0;
struct timeval tim;
FILE *fpsrc=NULL,*fpdst=NULL;
ImagenData source=NULL, output=NULL;
// Store number of partitions
partitions = atoi(argv[4]);
////////////////////////////////////////
//Reading kernel matrix
gettimeofday(&tim, NULL);
start = tim.tv_sec+(tim.tv_usec/1000000.0);
tstart = start;
kernelData kern=NULL;
if ( (kern = leerKernel(argv[2]))==NULL) {
// free(source);
// free(output);
return -1;
}
//The matrix kernel define the halo size to use with the image. The halo is zero when the image is not partitioned.
if (partitions==1) halo=0;
else halo = (kern->kernelY/2)*2;
gettimeofday(&tim, NULL);
treadk = treadk + (tim.tv_sec+(tim.tv_usec/1000000.0) - start);
////////////////////////////////////////
//Reading Image Header. Image properties: Magical number, comment, size and color resolution.
gettimeofday(&tim, NULL);
start = tim.tv_sec+(tim.tv_usec/1000000.0);
//Memory allocation based on number of partitions and halo size.
if ( (source = initimage(argv[1], &fpsrc, partitions, halo)) == NULL) {
return -1;
}
gettimeofday(&tim, NULL);
tread = tread + (tim.tv_sec+(tim.tv_usec/1000000.0) - start);
//Duplicate the image struct.
gettimeofday(&tim, NULL);
start = tim.tv_sec+(tim.tv_usec/1000000.0);
if ( (output = duplicateImageData(source, partitions, halo)) == NULL) {
return -1;
}
gettimeofday(&tim, NULL);
tcopy = tcopy + (tim.tv_sec+(tim.tv_usec/1000000.0) - start);
////////////////////////////////////////
//Initialize Image Storing file. Open the file and store the image header.
gettimeofday(&tim, NULL);
start = tim.tv_sec+(tim.tv_usec/1000000.0);
if (initfilestore(output, &fpdst, argv[3], &position)!=0) {
perror("Error: ");
// free(source);
// free(output);
return -1;
}
gettimeofday(&tim, NULL);
tstore = tstore + (tim.tv_sec+(tim.tv_usec/1000000.0) - start);
//////////////////////////////////////////////////////////////////////////////////////////////////
// CHUNK READING
//////////////////////////////////////////////////////////////////////////////////////////////////
int c=0, offset=0;
imagesize = source->altura*source->ancho;
partsize = (source->altura*source->ancho)/partitions;
// printf("%s ocupa %dx%d=%d pixels. Partitions=%d, halo=%d, partsize=%d pixels\n", argv[1], source->altura, source->ancho, imagesize, partitions, halo, partsize);
while (c < partitions) {
////////////////////////////////////////////////////////////////////////////////
//Reading Next chunk.
gettimeofday(&tim, NULL);
start = tim.tv_sec+(tim.tv_usec/1000000.0);
if (c==0) {
halosize = halo/2;
chunksize = partsize + (source->ancho*halosize);
offset = 0;
}
else if(c<partitions-1) {
halosize = halo;
chunksize = partsize + (source->ancho*halosize);
offset = (source->ancho*halo/2);
}
else {
halosize = halo/2;
chunksize = partsize + (source->ancho*halosize);
offset = (source->ancho*halo/2);
}
//DEBUG
// printf("\nRound = %d, position = %ld, partsize= %d, chunksize=%d pixels\n", c, position, partsize, chunksize);
if (readImage(source, &fpsrc, chunksize, halo/2, &position)) {
return -1;
}
gettimeofday(&tim, NULL);
tread = tread + (tim.tv_sec+(tim.tv_usec/1000000.0) - start);
//Duplicate the image chunk
gettimeofday(&tim, NULL);
start = tim.tv_sec+(tim.tv_usec/1000000.0);
if ( duplicateImageChunk(source, output, chunksize) ) {
return -1;
}
//DEBUG
// for (i=0;i<chunksize;i++)
// if (source->R[i]!=output->R[i] || source->G[i]!=output->G[i] || source->B[i]!=output->B[i]) printf("At position i=%d %d!=%d,%d!=%d,%d!=%d\n",i,source->R[i],output->R[i], source->G[i],output->G[i],source->B[i],output->B[i]);
gettimeofday(&tim, NULL);
tcopy = tcopy + (tim.tv_sec+(tim.tv_usec/1000000.0) - start);
//////////////////////////////////////////////////////////////////////////////////////////////////
// CHUNK CONVOLUTION
//////////////////////////////////////////////////////////////////////////////////////////////////
gettimeofday(&tim, NULL);
start = tim.tv_sec+(tim.tv_usec/1000000.0);
convolve2D(source->R, output->R, source->ancho, (source->altura/partitions)+halosize, kern->vkern, kern->kernelX, kern->kernelY);
convolve2D(source->G, output->G, source->ancho, (source->altura/partitions)+halosize, kern->vkern, kern->kernelX, kern->kernelY);
convolve2D(source->B, output->B, source->ancho, (source->altura/partitions)+halosize, kern->vkern, kern->kernelX, kern->kernelY);
gettimeofday(&tim, NULL);
tconv = tconv + (tim.tv_sec+(tim.tv_usec/1000000.0) - start);
//////////////////////////////////////////////////////////////////////////////////////////////////
// CHUNK SAVING
//////////////////////////////////////////////////////////////////////////////////////////////////
//Storing resulting image partition.
gettimeofday(&tim, NULL);
start = tim.tv_sec+(tim.tv_usec/1000000.0);
if (savingChunk(output, &fpdst, partsize, offset)) {
perror("Error: ");
// free(source);
// free(output);
return -1;
}
gettimeofday(&tim, NULL);
tstore = tstore + (tim.tv_sec+(tim.tv_usec/1000000.0) - start);
//Next partition
c++;
}
fclose(fpsrc);
fclose(fpdst);
freeImagestructure(&source);
freeImagestructure(&output);
gettimeofday(&tim, NULL);
tend = tim.tv_sec+(tim.tv_usec/1000000.0);
printf("Imatge: %s\n", argv[1]);
printf("ISizeX : %d\n", source->ancho);
printf("ISizeY : %d\n", source->altura);
printf("kSizeX : %d\n", kern->kernelX);
printf("kSizeY : %d\n", kern->kernelY);
printf("%.6lf seconds elapsed for Reading image file.\n", tread);
printf("%.6lf seconds elapsed for copying image structure.\n", tcopy);
printf("%.6lf seconds elapsed for Reading kernel matrix.\n", treadk);
printf("%.6lf seconds elapsed for make the convolution.\n", tconv);
printf("%.6lf seconds elapsed for writing the resulting image.\n", tstore);
printf("%.6lf seconds elapsed\n", tend-tstart);
return 0;
}