omkar pathak
omkar pathak

Reputation: 83

Sobel Edge detection in Python and Opencv

the following code in python detects edge using sobel operator in horizontal as well as vertical direction

import cv2
import numpy as np

img = cv2.imread('image.bmp', cv2.IMREAD_GRAYSCALE)
rows, cols = img.shape

sobel_horizontal = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=5)
sobel_vertical = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=5)

cv2.imshow('Original', img)
cv2.imshow('Sobel horizontal', sobel_horizontal)
cv2.imshow('Sobel vertical', sobel_vertical)

cv2.waitKey(0)

is there any logic to detect the edge from left to right and vice versa?

Upvotes: 4

Views: 24503

Answers (2)

MD. Saiful Islam
MD. Saiful Islam

Reputation: 459

you can follow the code.

import cv2
img = cv2.imread('type you images path here / image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
x = cv2.Sobel(gray, ddept, 1,0, ksize=3, scale=1)
y = cv2.Sobel(gray, ddept, 0,1, ksize=3, scale=1)
absx= cv2.convertScaleAbs(x)
absy = cv2.convertScaleAbs(y)
edge = cv2.addWeighted(absx, 0.5, absy, 0.5,0)
cv2.imshow('edge', edge)
cv2.waitKey(0)
cv2.destroyAllWindows()

or you could download the file from Github.

Github link : https://github.com/Angileca/Sobel-edge-detection

Upvotes: 1

alexisrozhkov
alexisrozhkov

Reputation: 1632

When you use double (CV_64F) as a destination type, you can distinguish between left/right (or up/down) edges by the sign of pixel value in the output image (remember that sobel is a smoothed numerical approximation of derivative, so this is quite natural)

Upvotes: 2

Related Questions