I'm trying to understand the Sobel convolution from cv2
in Python.
According to documentation the Sobel kernel is
-1 0 1
-2 0 2
-1 0 1
So, I tried to apply it to the following img
(a binary 3x3
array):
0 1 0
1 0 1
0 1 0
Now, I have a problem to interpret the output. I computed by hand and got different result. As fas as I know, I have to center the kernel at each pixel (i,j)
and multiply element wise and sum.
So, the first entry in output should be 2
. The program returns 0
.
Am I wrong? I hope so.
Code
import cv2
import numpy as np
img = np.array([[0,1,0],[1,0,1],[0,1,0]]).astype(float)
# Output dtype = cv2.CV_8U
sobelx8u = cv2.Sobel(img,cv2.CV_8U,1,0,ksize=3)
# Output dtype = cv2.CV_64F. Then take its absolute and convert to cv2.CV_8U
sobelx64f = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)
abs_sobel64f = np.absolute(sobelx64f)
sobel_8u = np.uint8(abs_sobel64f)
print 'img'
print img
print 'sobelx8u'
print sobelx8u
print 'sobelx64f'
print sobelx64f
print 'abs_sobel64f'
print abs_sobel64f
print 'sobel_8u'
print sobel_8u
Output
img
[[ 0. 1. 0.]
[ 1. 0. 1.]
[ 0. 1. 0.]]
sobelx8u
[[0 0 0]
[0 0 0]
[0 0 0]]
sobelx64f
[[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]]
abs_sobel64f
[[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]]
sobel_8u
[[0 0 0]
[0 0 0]
[0 0 0]]