| 1 |
{ A simple edge-detection by calculating gradient (actually, |
| 2 |
the length of the gradient vector) with Sobel operator, in CastleScript. |
| 3 |
See [http://en.wikipedia.org/wiki/Sobel_operator]. |
| 4 |
Source image filename is constant below, you can change it to |
| 5 |
any RGB(+possibly with alpha) existing image filename. |
| 6 |
|
| 7 |
Note that this may take a while for larger images. |
| 8 |
With current optimizations, it takes 6.5 seconds for 640 x 480 image. |
| 9 |
Hm, quite fast actually (before profiling, it was 93 seconds...). |
| 10 |
For other image sizes --- do the math, time is proportional to pixels count. |
| 11 |
|
| 12 |
Take into account that CastleScript is not speed-optimal, |
| 13 |
it's image functions are comfortable but not fast (3-byte convertion |
| 14 |
between 3-single/float mix, for starters), we try to catch |
| 15 |
FP exceptions immediately (which means we don't use FP unit efficiently) |
| 16 |
and such. If you want optimal language, any scripting lang is bad choice, |
| 17 |
rather use ObjectPascal with Castle Game Engine :). |
| 18 |
} |
| 19 |
|
| 20 |
function main() |
| 21 |
helper_img := image_load('castle-data:/test_texture.png'); |
| 22 |
|
| 23 |
{ copy helper_img, to copy it's size and alpha channel } |
| 24 |
result := helper_img; |
| 25 |
|
| 26 |
for (i, 0, image_width(result) - 1, |
| 27 |
for (j, 0, image_height(result) - 1, |
| 28 |
x := |
| 29 |
if(i > 0, |
| 30 |
if (j > 0, grayscale(image_get_color(helper_img, i-1, j-1)), 0) + |
| 31 |
2 * grayscale(image_get_color(helper_img, i-1, j)) + |
| 32 |
if (j < image_height(result) - 1, grayscale(image_get_color(helper_img, i-1, j+1)), 0), |
| 33 |
0) - |
| 34 |
if(i < image_width(result) - 1, |
| 35 |
if (j > 0, grayscale(image_get_color(helper_img, i+1, j-1)), 0) + |
| 36 |
2 * grayscale(image_get_color(helper_img, i+1, j)) + |
| 37 |
if (j < image_height(result) - 1, grayscale(image_get_color(helper_img, i+1, j+1)), 0), |
| 38 |
0); |
| 39 |
y := |
| 40 |
if(j > 0, |
| 41 |
if (i > 0, grayscale(image_get_color(helper_img, i-1, j-1)), 0) + |
| 42 |
2 * grayscale(image_get_color(helper_img, i, j-1)) + |
| 43 |
if (i < image_width(result) - 1, grayscale(image_get_color(helper_img, i+1, j-1)), 0), |
| 44 |
0) - |
| 45 |
if(j < image_height(result) - 1, |
| 46 |
if (i > 0, grayscale(image_get_color(helper_img, i-1, j+1)), 0) + |
| 47 |
2 * grayscale(image_get_color(helper_img, i, j+1)) + |
| 48 |
if (i < image_width(result) - 1, grayscale(image_get_color(helper_img, i+1, j+1)), 0), |
| 49 |
0); |
| 50 |
z := sqrt(sqr(x) + sqr(y)); |
| 51 |
image_set_color(result, i, j, vector(z, z, z)))) |