I'm trying to code a simple convolution loop for image processing. It seems to work fine when the kernel adds up to 1 i.e smoothing filter.
But when using an edge detection filter, weird values appear:
for i in range(img.shape[1]):
index = []
for j in range(order):
index.append(i j)
array_aux=img_processed[:,index]
img_final[:,i]=np.sum(array_aux*kernel_x,axis=1)
I'm applying a 1D kernel that im extending to the full height of the picture and convolving by multiplying that extended kernel with the columns needed and adding up all values. I´m using cv2.BORDER_REFLECT_101 padding:
Image: Kernel: Final Image:
[ 85 85 85 85 85] [ 1 0 -1] [ 0 0 0 0 0]
[ 85 85 85 85 85] [ 1 0 -1] [ 0 0 0 0 0]
[ 84 84 84 84 84] [ 1 0 -1] [ 0 0 0 0 0]
... ... ...
[106 136 179 170 152] [ 1 0 -1] [ 0 183 222 27 6]
[113 129 172 175 153] [ 1 0 -1] [ 0 197 210 19 30]
[123 125 168 183 156] [ 1 0 -1] [ 0 211 198 12 57]
as you can see while the first three row seem to be fine, the last 3 are wrong as negative number are expected. What's going on?
CodePudding user response:
Actually, your issue seems to be img_final
, which I suspect is also of dtype uint8
.
If you do an operation between a float and an integer, the result will correctly be a float. But when you try to put a float in a uint8 array, it will get cast to that.
>>> img_final = np.zeros((3, 3), dtype=np.uint8)
>>> img_final[0,0] = -2.5
>>> img_final
array([[254, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0]], dtype=uint8)
Just set the correct type for img_final
and it should be fine. If you want to handle positive and negative integers, int32
should suffice.