Programas C/C++ utilizando arrays (2)

Autor: rubens
Data: 28/04/2009

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

Módulo C++

 1 void dilate_(int h, int w, uint8 *input, int se[9], int hh, int ww, uint8 *output)
 2 {
 3     int H = h + 2;
 4     int W = w + 2;
 5     uint8 *binput = add_border(input, w, h, 0);
 6     nv *neigh = neighvec(se, W);
 7 
 8     uint8 *pp = binput + W + 1;
 9     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

 1 from numpyobj2 import dilate
 2 
 3 arr = array([[0,0,0,0,0,0,0,0,0,0],
 4              [0,0,0,0,0,0,0,0,0,0],
 5              [0,0,1,2,3,4,3,2,0,0],
 6              [0,0,1,2,3,4,3,2,0,0],
 7              [0,0,1,2,3,4,3,2,0,0],
 8              [0,0,1,2,3,4,3,2,0,0],
 9              [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.347 ms
 mmdil: 1.036 ms
    OK: 1