Sobel edge detection using opencv

pr22 picture pr22 · Jul 4, 2018 · Viewed 7.3k times · Source

I am using the built-in Sobel edge operation in openCV for some image processing purpose but the results are not as expected for the function.

sobel=cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3)
cv2.imshow('Sobel Image',sobel)

I am attaching a sample image of the input image and the resultant output which I have got. Please help me regarding this. On the left is the input image and on the right is the resultant image.

enter image description here

Answer

Gustavo Kaneto picture Gustavo Kaneto · Mar 15, 2020

You have to make two sobel operations and blend them. Also, be sure you are working on a gray-scaled image, otherwise I think it will process each channel separately..

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

grad_x = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)
grad_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)

abs_grad_x = cv2.convertScaleAbs(grad_x)
abs_grad_y = cv2.convertScaleAbs(grad_y)

grad = cv2.addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0)

cv2.imshow('grad X',grad_x)
cv2.imshow('grad Y',grad_y)
cv2.imshow('Sobel Image',grad)
cv2.waitKey()

The results for x, y and blended image are:

enter image description here

If you need to reduce noise, you may apply a Gaussian Blur. Refer to: https://docs.opencv.org/4.2.0/d2/d2c/tutorial_sobel_derivatives.html