views:

555

answers:

1

Hi

I am trying to perform a 2d convolution in python using numpy

I have a 2d array as follows with kernel H_r for the rows and H_c for the columns

data = np.zeros((nr, nc), dtype=np.float32)

#fill array with some data here then convolve

for r in range(nr):
    data[r,:] = np.convolve(data[r,:], H_r, 'same')

for c in range(nc):
    data[:,c] = np.convolve(data[:,c], H_c, 'same')

data = data.astype(np.uint8);

It does not produce the output that I was expecting, does this code look OK, I think the problem is with the casting from float32 to 8bit. Whats the best way to do this

Thanks

+1  A: 

Since you already have your kernel separated you should simply use the sepfir2d function from scipy:

from scipy.signal import sepfir2d
convolved = sepfir2d(data, H_r, H_c)

On the other hand, the code you have there looks all right ...

dudemeister
Hi Dudemaster, I think the problem is that I am casting the output to 8bit using this command data = np.array(data,dtype=np.int8)Is this OK
mikip
@mikip are your numbers in the range of -128 to 127 before you convert them to 8bit? If not, then that is drastically changing your output.
Justin Peel
Well that really depends on the implementation of the convolve and also your kernel. It might be worth a try to cast both your kernel and data to float or int32 at least. Note that any decent 8bit convolution algorithm should work with (at least) 16bit temporary values because the summing during the convolve can easily overfloat 8bit values, depending on the kernel.
dudemeister