Programas C/C++ utilizando arrays (2)

Autor: rubens
Data: 28/04/2009

Uma implementação da dilatação em C++

Módulo C++

01. void dilate_(int h, int w, uint8 *input, int se[9], int hh, int ww, uint8 *output)
02. {
03.     int H = h + 2;
04.     int W = w + 2;
05.     uint8 *binput = add_border(input, w, h, 0);
06.     nv *neigh = neighvec(se, W);
07. 
08.     uint8 *pp = binput + W + 1;
09.     uint8 *po = output;
10.     for(int i = 0; i < h; i ++) {
11.         for(int j = 0; j < w; j++) {
12.             *po = *pp;
13.             for(int k = 0; k < neigh->len; k ++) {
14.                 uint8 v = *(pp + neigh->off[k]);
15.                 if(v > *po) *po = v;
16.             }
17.             pp++;
18.             po++;
19.         }
20.         pp += 2;
21.     }
22. }
1. void dilate_(int DIM1, int DIM2, unsigned char *IN_ARRAY2,
2.              int IN_ARRAY1[9],
3.              int DIM1, int DIM2, unsigned char *INPLACE_ARRAY2);
OK [C/C++ extension is up-to-date]

Módulo Python

1. def dilate(a, se):
2.     from numpy import zeros_like
3.     c = zeros_like(a)
4.     st = dilate_(a, se, c)
5.     return c

Exemplos de uso

01. from numpyobj2 import dilate
02. 
03. arr = array([[0,0,0,0,0,0,0,0,0,0],
04.              [0,0,0,0,0,0,0,0,0,0],
05.              [0,0,1,2,3,4,3,2,0,0],
06.              [0,0,1,2,3,4,3,2,0,0],
07.              [0,0,1,2,3,4,3,2,0,0],
08.              [0,0,1,2,3,4,3,2,0,0],
09.              [0,0,1,2,3,4,3,2,0,0],
10.              [0,0,0,1,1,1,1,0,0,0],
11.              [0,0,0,0,0,0,0,0,0,0],
12.              [0,0,0,0,0,0,0,0,0,0]], uint8)
13. 
14. arr1 = mmdil(arr)
15. arr2 = dilate(arr, [0,1,0,1,1,1,0,1,0])
16. print arr2
17. print
18. 
19. print 'OK =', mmisequal(arr1, arr2)
[[0 0 0 0 0 0 0 0 0 0]
 [0 0 1 2 3 4 3 2 0 0]
 [0 1 2 3 4 4 4 3 2 0]
 [0 1 2 3 4 4 4 3 2 0]
 [0 1 2 3 4 4 4 3 2 0]
 [0 1 2 3 4 4 4 3 2 0]
 [0 1 2 3 4 4 4 3 2 0]
 [0 0 1 2 3 4 3 2 0 0]
 [0 0 0 1 1 1 1 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]]

OK = 1.0
1. arr = mmreadgray('cameraman.tif')
2. 
3. t0 = time.time()*1000
4. arr1 = mmdil(arr)
5. t1 = time.time()*1000
6. arr2 = dilate(arr, [0,1,0,1,1,1,0,1,0])
7. t2 = time.time()*1000
8. 
9. print 'dilate: %5.3f ms\n mmdil: %5.3f ms\n    OK: %d' % (t1-t0, t2-t1, mmisequal(arr1, arr2))
dilate: 2.332 ms
 mmdil: 1.049 ms
    OK: 1