-
Notifications
You must be signed in to change notification settings - Fork 19
/
change.c
100 lines (73 loc) · 2.52 KB
/
change.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
/*
Compile with emcc with:
emcc -o change.js change.c -lm -O3 -s WASM=1 -s EXPORTED_FUNCTIONS="['_change']" -s BINARYEN_IMPRECISE=1
*/
#include<stdio.h>
#include<math.h>
#include<stdbool.h>
#include<stdlib.h>
#include<string.h>
#define WIDTH 600
#define HEIGHT 480
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
int grayData[WIDTH * HEIGHT];
int getPixel(int x, int y) {
if (x < 0 || y < 0) return 0;
if (x >= (WIDTH) || y >= (HEIGHT)) return 0;
return (grayData[((WIDTH * y) + x)]);
}
void sobel(unsigned char * data, int width, int height) {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int goffset = ((WIDTH * y) + x) << 2; //multiply by 4
int r = data[goffset];
int g = data[goffset + 1];
int b = data[goffset + 2];
int avg = (r >> 2) + (g >> 1) + (b >> 3);
grayData[((WIDTH * y) + x)] = avg;
int doffset = ((WIDTH * y) + x) << 2;
data[doffset] = avg;
data[doffset + 1] = avg;
data[doffset + 2] = avg;
data[doffset + 3] = 255;
}
}
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int newX;
int newY;
if ((x <= 0 || x >= width - 1) || (y <= 0 || y >= height - 1)) {
newX = 0;
newY = 0;
} else {
newX = (
(-1 * getPixel(x - 1, y - 1)) +
(getPixel(x + 1, y - 1)) +
(-1 * (getPixel(x - 1, y) << 1)) +
(getPixel(x + 1, y) << 1) +
(-1 * getPixel(x - 1, y + 1)) +
(getPixel(x + 1, y + 1))
);
newY = (
(-1 * getPixel(x - 1, y - 1)) +
(-1 * (getPixel(x, y - 1) << 1)) +
(-1 * getPixel(x + 1, y - 1)) +
(getPixel(x - 1, y + 1)) +
(getPixel(x, y + 1) << 1) +
(getPixel(x + 1, y + 1))
);
}
int mag = sqrt((newX * newX) + (newY * newY));
if (mag > 255) mag = 255;
int offset = ((WIDTH * y) + x) << 2; //multiply by 4
data[offset] = 255 - mag;
data[offset + 1] = 255 - mag;
data[offset + 2] = 255 - mag;
data[offset + 3] = 255;
}
}
}
void change(unsigned char * data, int cols, int rows) {
sobel(data, cols, rows);
}