-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimageBW.c
639 lines (517 loc) · 17 KB
/
imageBW.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
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
/// imageBW - A simple image processing module for BW images
/// represented using run-length encoding (RLE)
///
/// This module is part of a programming project
/// for the course AED, DETI / UA.PT
///
/// You may freely use and modify this code, at your own risk,
/// as long as you give proper credit to the original and subsequent authors.
///
/// The AED Team <[email protected], [email protected], ...>
/// 2024
// Student authors (fill in below):
// NMec:
// Name:
// NMec:
// Name:
//
// Date:
//
#include "imageBW.h"
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "instrumentation.h"
// The data structure
//
// A BW image is stored in a structure containing 3 fields:
// Two integers store the image width and height.
// The other field is a pointer to an array that stores the pointers
// to the RLE compressed image rows.
//
// Clients should use images only through variables of type Image,
// which are pointers to the image structure, and should not access the
// structure fields directly.
// Constant value --- Use them throughout your code
// const uint8 BLACK = 1; // Black pixel value, defined on .h
// const uint8 WHITE = 0; // White pixel value, defined on .h
const int EOR = -1; // Stored as the last element of a RLE row
// Internal structure for storing RLE BW images
struct image {
uint32 width;
uint32 height;
int** row; // pointer to an array of pointers referencing the compressed rows
};
// This module follows "design-by-contract" principles.
// Read `Design-by-Contract.md` for more details.
/// Error handling functions
// In this module, only functions dealing with memory allocation or
// file (I/O) operations use defensive techniques.
// When one of these functions fails,
// it immediately prints an error and exits the program.
// This fail-fast approach to error handling is simpler for the programmer.
// Use the following function to check a condition
// and exit if it fails.
// Check a condition and if false, print failmsg and exit.
static void check(int condition, const char* failmsg) {
if (!condition) {
perror(failmsg);
exit(errno || 255);
}
}
/// Init Image library. (Call once!)
/// Currently, simply calibrate instrumentation and set names of counters.
void ImageInit(void) { ///
InstrCalibrate();
InstrName[0] = "pixmem"; // InstrCount[0] will count pixel array acesses
// Name other counters here...
}
// Macros to simplify accessing instrumentation counters:
#define PIXMEM InstrCount[0]
// Add more macros here...
// TIP: Search for PIXMEM or InstrCount to see where it is incremented!
/// Auxiliary (static) functions
/// Create the header of an image data structure
/// And allocate the array of pointers to RLE rows
static Image AllocateImageHeader(uint32 width, uint32 height) {
assert(width > 0 && height > 0);
Image newHeader = malloc(sizeof(struct image));
check(newHeader != NULL, "malloc");
newHeader->width = width;
newHeader->height = height;
// Allocating the array of pointers to RLE rows
newHeader->row = malloc(height * sizeof(int*));
check(newHeader->row != NULL, "malloc");
return newHeader;
}
/// Allocate an array to store a RLE row with n elements
static int* AllocateRLERowArray(uint32 n) {
assert(n > 2);
int* newArray = malloc(n * sizeof(int));
check(newArray != NULL, "malloc");
return newArray;
}
/// Compute the number of runs of a non-compressed (RAW) image row
static uint32 GetNumRunsInRAWRow(uint32 image_width, const uint8* RAW_row) {
assert(image_width > 0);
assert(RAW_row != NULL);
// How many runs?
uint32 num_runs = 1;
for (uint32 i = 1; i < image_width; i++) {
if (RAW_row[i] != RAW_row[i - 1]) {
num_runs++;
}
}
return num_runs;
}
/// Get the number of runs of a compressed RLE image row
static uint32 GetNumRunsInRLERow(const int* RLE_row) {
assert(RLE_row != NULL);
// Go through the RLE_row until EOR is found
// Discard RLE_row[0], since it is a pixel color
uint32 num_runs = 0;
uint32 i = 1;
while (RLE_row[i] != EOR) {
num_runs++;
i++;
}
return num_runs;
}
/// Get the number of elements of an array storing a compressed RLE image row
static uint32 GetSizeRLERowArray(const int* RLE_row) {
assert(RLE_row != NULL);
// Go through the array until EOR is found
uint32 i = 0;
while (RLE_row[i] != EOR) {
i++;
}
return (i + 1);
}
/// Compress into RLE format a RAW image row
/// Allocates and returns the array storing the image row in RLE format
static int* CompressRow(uint32 image_width, const uint8* RAW_row) {
assert(image_width > 0);
assert(RAW_row != NULL);
// How many runs?
uint32 num_runs = GetNumRunsInRAWRow(image_width, RAW_row);
// Allocate the RLE row array
int* RLE_row = malloc((num_runs + 2) * sizeof(int));
check(RLE_row != NULL, "malloc");
// Go through the RAW_row
RLE_row[0] = (int)RAW_row[0]; // Initial pixel value
uint32 index = 1;
int num_pixels = 1;
for (uint32 i = 1; i < image_width; i++) {
if (RAW_row[i] != RAW_row[i - 1]) {
RLE_row[index++] = num_pixels;
num_pixels = 0;
}
num_pixels++;
}
RLE_row[index++] = num_pixels;
RLE_row[index] = EOR; // Reached the end of the row
return RLE_row;
}
static uint8* UncompressRow(uint32 image_width, const int* RLE_row) {
assert(image_width > 0);
assert(RLE_row != NULL);
// The uncompressed row
uint8* row = (uint8*)malloc(image_width * sizeof(uint8));
check(row != NULL, "malloc");
// Go through the RLE_row until EOR is found
int pixel_value = RLE_row[0];
uint32 i = 1;
uint32 dest_i = 0;
while (RLE_row[i] != EOR) {
// For each run
for (int aux = 0; aux < RLE_row[i]; aux++) {
row[dest_i++] = (uint8)pixel_value;
}
// Next run
i++;
pixel_value ^= 1;
}
return row;
}
// Add your auxiliary functions here...
/// Image management functions
/// Create a new BW image, either BLACK or WHITE.
/// width, height : the dimensions of the new image.
/// val: the pixel color (BLACK or WHITE).
/// Requires: width and height must be non-negative, val is either BLACK or
/// WHITE.
///
/// On success, a new image is returned.
/// (The caller is responsible for destroying the returned image!)
Image ImageCreate(uint32 width, uint32 height, uint8 val) {
assert(width > 0 && height > 0);
assert(val == WHITE || val == BLACK);
Image newImage = AllocateImageHeader(width, height);
// All image pixels have the same value
int pixel_value = (int)val;
// Creating the image rows, each row has just 1 run of pixels
// Each row is represented by an array of 3 elements [value,length,EOR]
for (uint32 i = 0; i < height; i++) {
newImage->row[i] = AllocateRLERowArray(3);
newImage->row[i][0] = pixel_value;
newImage->row[i][1] = (int)width;
newImage->row[i][2] = EOR;
}
return newImage;
}
/// Create a new BW image, with a perfect CHESSBOARD pattern.
/// width, height : the dimensions of the new image.
/// square_edge : the lenght of the edges of the sqares making up the
/// chessboard pattern.
/// first_value: the pixel color (BLACK or WHITE) of the
/// first image pixel.
/// Requires: width and height must be non-negative, val is either BLACK or
/// WHITE.
/// Requires: for the squares, width and height must be multiples of the
/// edge lenght of the squares
///
/// On success, a new image is returned.
/// (The caller is responsible for destroying the returned image!)
Image ImageCreateChessboard(uint32 width, uint32 height, uint32 square_edge,
uint8 first_value) {
// COMPLETE THE CODE
// ...
return NULL;
}
/// Destroy the image pointed to by (*imgp).
/// imgp : address of an Image variable.
/// If (*imgp)==NULL, no operation is performed.
/// Ensures: (*imgp)==NULL.
/// Should never fail.
void ImageDestroy(Image* imgp) {
assert(imgp != NULL);
Image img = *imgp;
for (uint32 i = 0; i < img->height; i++) {
free(img->row[i]);
}
free(img->row);
free(img);
*imgp = NULL;
}
/// Printing on the console
/// Output the raw BW image
void ImageRAWPrint(const Image img) {
assert(img != NULL);
printf("width = %d height = %d\n", img->width, img->height);
printf("RAW image:\n");
// Print the pixels of each image row
for (uint32 i = 0; i < img->height; i++) {
// The value of the first pixel in the current row
int pixel_value = img->row[i][0];
for (uint32 j = 1; img->row[i][j] != EOR; j++) {
// Print the current run of pixels
for (int k = 0; k < img->row[i][j]; k++) {
printf("%d", pixel_value);
}
// Switch (XOR) to the pixel value for the next run, if any
pixel_value ^= 1;
}
// At current row end
printf("\n");
}
printf("\n");
}
/// Output the compressed RLE image
void ImageRLEPrint(const Image img) {
assert(img != NULL);
printf("width = %d height = %d\n", img->width, img->height);
printf("RLE encoding:\n");
// Print the compressed rows information
for (uint32 i = 0; i < img->height; i++) {
uint32 j;
for (j = 0; img->row[i][j] != EOR; j++) {
printf("%d ", img->row[i][j]);
}
printf("%d\n", img->row[i][j]);
}
printf("\n");
}
/// PBM BW file operations
// See PBM format specification: http://netpbm.sourceforge.net/doc/pbm.html
// Auxiliary function
static void unpackBits(int nbytes, const uint8 bytes[], uint8 raw_row[]) {
// bitmask starts at top bit
int offset = 0;
uint8 mask = 1 << (7 - offset);
while (offset < 8) { // or (mask > 0)
for (int b = 0; b < nbytes; b++) {
raw_row[8 * b + offset] = (bytes[b] & mask) != 0;
}
mask >>= 1;
offset++;
}
}
// Auxiliary function
static void packBits(int nbytes, uint8 bytes[], const uint8 raw_row[]) {
// bitmask starts at top bit
int offset = 0;
uint8 mask = 1 << (7 - offset);
while (offset < 8) { // or (mask > 0)
for (int b = 0; b < nbytes; b++) {
if (offset == 0) bytes[b] = 0;
bytes[b] |= raw_row[8 * b + offset] ? mask : 0;
}
mask >>= 1;
offset++;
}
}
// Match and skip 0 or more comment lines in file f.
// Comments start with a # and continue until the end-of-line, inclusive.
// Returns the number of comments skipped.
static int skipComments(FILE* f) {
char c;
int i = 0;
while (fscanf(f, "#%*[^\n]%c", &c) == 1 && c == '\n') {
i++;
}
return i;
}
/// Load a raw PBM file.
/// Only binary PBM files are accepted.
/// On success, a new image is returned.
/// (The caller is responsible for destroying the returned image!)
Image ImageLoad(const char* filename) { ///
int w, h;
char c;
FILE* f = NULL;
Image img = NULL;
check((f = fopen(filename, "rb")) != NULL, "Open failed");
// Parse PBM header
check(fscanf(f, "P%c ", &c) == 1 && c == '4', "Invalid file format");
skipComments(f);
check(fscanf(f, "%d ", &w) == 1 && w >= 0, "Invalid width");
skipComments(f);
check(fscanf(f, "%d", &h) == 1 && h >= 0, "Invalid height");
check(fscanf(f, "%c", &c) == 1 && isspace(c), "Whitespace expected");
// Allocate image
img = AllocateImageHeader(w, h);
// Read pixels
int nbytes = (w + 8 - 1) / 8; // number of bytes for each row
// using VLAs...
uint8 bytes[nbytes];
uint8 raw_row[nbytes * 8];
for (uint32 i = 0; i < img->height; i++) {
check(fread(bytes, sizeof(uint8), nbytes, f) == (size_t)nbytes,
"Reading pixels");
unpackBits(nbytes, bytes, raw_row);
img->row[i] = CompressRow(w, raw_row);
}
fclose(f);
return img;
}
/// Save image to PBM file.
/// On success, returns unspecified integer. (No need to check!)
/// On failure, does not return, EXITS program!
int ImageSave(const Image img, const char* filename) { ///
assert(img != NULL);
int w = img->width;
int h = img->height;
FILE* f = NULL;
check((f = fopen(filename, "wb")) != NULL, "Open failed");
check(fprintf(f, "P4\n%d %d\n", w, h) > 0, "Writing header failed");
// Write pixels
int nbytes = (w + 8 - 1) / 8; // number of bytes for each row
// using VLAs...
uint8 bytes[nbytes];
// unit8 raw_row[nbytes*8];
for (uint32 i = 0; i < img->height; i++) {
// UncompressRow...
uint8* raw_row = UncompressRow(nbytes * 8, img->row[i]);
// Fill padding pixels with WHITE
memset(raw_row + w, WHITE, nbytes * 8 - w);
packBits(nbytes, bytes, raw_row);
size_t written = fwrite(bytes, sizeof(uint8), nbytes, f);
check(written == (size_t)nbytes, "Writing pixels failed");
free(raw_row);
}
// Cleanup
fclose(f);
return 0;
}
/// Information queries
/// Get image width
int ImageWidth(const Image img) {
assert(img != NULL);
return img->width;
}
/// Get image height
int ImageHeight(const Image img) {
assert(img != NULL);
return img->height;
}
/// Image comparison
int ImageIsEqual(const Image img1, const Image img2) {
assert(img1 != NULL && img2 != NULL);
// COMPLETE THE CODE
// ...
return 0;
}
int ImageIsDifferent(const Image img1, const Image img2) {
assert(img1 != NULL && img2 != NULL);
return !ImageIsEqual(img1, img2);
}
/// Boolean Operations on image pixels
/// These functions apply boolean operations to images,
/// returning a new image as a result.
///
/// Operand images are left untouched and must be of the same size.
///
/// On success, a new image is returned.
/// (The caller is responsible for destroying the returned image!)
Image ImageNEG(const Image img) {
assert(img != NULL);
uint32 width = img->width;
uint32 height = img->height;
Image newImage = AllocateImageHeader(width, height);
// Directly copying the rows, one by one
// And changing the value of row[i][0]
for (uint32 i = 0; i < height; i++) {
uint32 num_elems = GetSizeRLERowArray(img->row[i]);
newImage->row[i] = AllocateRLERowArray(num_elems);
memcpy(newImage->row[i], img->row[i], num_elems * sizeof(int));
newImage->row[i][0] ^= 1; // Just negate the value of the first pixel run
}
return newImage;
}
Image ImageAND(const Image img1, const Image img2) {
assert(img1 != NULL && img2 != NULL);
// COMPLETE THE CODE
// You might consider using the UncompressRow and CompressRow auxiliary files
// Or devise a more efficient alternative
// ...
return NULL;
}
Image ImageOR(const Image img1, const Image img2) {
assert(img1 != NULL && img2 != NULL);
// COMPLETE THE CODE
// You might consider using the UncompressRow and CompressRow auxiliary files
// Or devise a more efficient alternative
// ...
return NULL;
}
Image ImageXOR(Image img1, Image img2) {
assert(img1 != NULL && img2 != NULL);
// COMPLETE THE CODE
// You might consider using the UncompressRow and CompressRow auxiliary files
// Or devise a more efficient alternative
// ...
return NULL;
}
/// Geometric transformations
/// These functions apply geometric transformations to an image,
/// returning a new image as a result.
///
/// On success, a new image is returned.
/// (The caller is responsible for destroying the returned image!)
/// Mirror an image = flip top-bottom.
/// Returns a mirrored version of the image.
/// Ensures: The original img is not modified.
///
/// On success, a new image is returned.
/// (The caller is responsible for destroying the returned image!)
Image ImageHorizontalMirror(const Image img) {
assert(img != NULL);
uint32 width = img->width;
uint32 height = img->height;
Image newImage = AllocateImageHeader(width, height);
// COMPLETE THE CODE
// ...
return newImage;
}
/// Mirror an image = flip left-right.
/// Returns a mirrored version of the image.
/// Ensures: The original img is not modified.
///
/// On success, a new image is returned.
/// (The caller is responsible for destroying the returned image!)
Image ImageVerticalMirror(const Image img) {
assert(img != NULL);
uint32 width = img->width;
uint32 height = img->height;
Image newImage = AllocateImageHeader(width, height);
// COMPLETE THE CODE
// ...
return newImage;
}
/// Replicate img2 at the bottom of imag1, creating a larger image
/// Requires: the width of the two images must be the same.
/// Returns the new larger image.
/// Ensures: The original images are not modified.
///
/// On success, a new image is returned.
/// (The caller is responsible for destroying the returned image!)
Image ImageReplicateAtBottom(const Image img1, const Image img2) {
assert(img1 != NULL && img2 != NULL);
assert(img1->width == img2->width);
uint32 new_width = img1->width;
uint32 new_height = img1->height + img2->height;
Image newImage = AllocateImageHeader(new_width, new_height);
// COMPLETE THE CODE
// ...
return newImage;
}
/// Replicate img2 to the right of imag1, creating a larger image
/// Requires: the height of the two images must be the same.
/// Returns the new larger image.
/// Ensures: The original images are not modified.
///
/// On success, a new image is returned.
/// (The caller is responsible for destroying the returned image!)
Image ImageReplicateAtRight(const Image img1, const Image img2) {
assert(img1 != NULL && img2 != NULL);
assert(img1->height == img2->height);
uint32 new_width = img1->width + img2->width;
uint32 new_height = img1->height;
Image newImage = AllocateImageHeader(new_width, new_height);
// COMPLETE THE CODE
// ...
return newImage;
}