# Edge extraction with python + OpenCV (Sobel filter, Laplacian filter)

How to find the differential filter, basics http://qiita.com/shim0mura/items/5d3cbef873f2dd81d82c

OpenCV has the ability to apply Sobel and Laplacian filters.

## Sobel filter

`cv2.Sobel(src, ddepth, dx, dy[, dst[, ksize[, scale[, delta[, borderType]]]]]) → dst` http://docs.opencv.org/3.0-last-rst/modules/imgproc/doc/filtering.html?highlight=laplacian#sobel

--src: Input image --dst: Output image --ddepth: Output color depth --dx: Derivative order in the x direction --dy: Derivative order in the y direction --ksize: Specify kernel size 1, 3, 5, 7

It says that when the kernel size is 1, a 1x3 kernel or a 3x1 kernel is used, but when k = 5,7, it seems like this. http://stackoverflow.com/questions/9567882/sobel-filter-kernel-of-large-size

``````import cv2
from matplotlib import pyplot as plt

sobelx = cv2.Sobel(img, cv2.CV_32F, 1, 0, ksize=3)
sobely = cv2.Sobel(img, cv2.CV_32F, 0, 1, ksize=3)
sobelx5 = cv2.Sobel(img, cv2.CV_32F, 1, 0, ksize=5)
sobely5 = cv2.Sobel(img, cv2.CV_32F, 0, 1, ksize=5)

plt.subplot(2,2,1),plt.imshow(sobelx,cmap = 'gray')
plt.title('Sobel X k=3'), plt.xticks([]), plt.yticks([])
plt.subplot(2,2,2),plt.imshow(sobely,cmap = 'gray')
plt.title('Sobel Y k=3'), plt.xticks([]), plt.yticks([])
plt.subplot(2,2,3),plt.imshow(sobelx5,cmap = 'gray')
plt.title('Sobel X k=5'), plt.xticks([]), plt.yticks([])
plt.subplot(2,2,4),plt.imshow(sobely5,cmap = 'gray')
plt.title('Sobel Y k=5'), plt.xticks([]), plt.yticks([])
plt.show()
``````

result:

The line is darker and the blur is stronger when k = 5 than when k = 3.

## Laplacian filter

`cv2.Laplacian(src, ddepth[, dst[, ksize[, scale[, delta[, borderType]]]]]) → dst` http://docs.opencv.org/3.0-last-rst/modules/imgproc/doc/filtering.html?highlight=laplacian#laplacian

--src: Input image --dst: Output image --ddepth: Output color depth --ksize: kernel size

Since it is a Laplacian, it does not need to specify the direction unlike the one with the first derivative.

``````import cv2
from matplotlib import pyplot as plt

lap = cv2.Laplacian(img, cv2.CV_32F)
lap5 = cv2.Laplacian(img, cv2.CV_32F,ksize=3)

plt.subplot(1,2,1),plt.imshow(lap,cmap = 'gray')
plt.title('Laplacian'), plt.xticks([]), plt.yticks([])
plt.subplot(1,2,2),plt.imshow(lap5,cmap = 'gray')
plt.title('Laplacian k=3'), plt.xticks([]), plt.yticks([])

plt.show()

``````

result:

reference: