Published in

MLearning.ai

# How to perform Edge Detection using Sobel X and Sobel Y in cv2 — Easy Explanation

So in today’s blog, we are going to see the magic of edge detection using Sobel X and Sobel Y in cv2. Sobel X and Sobel Y are first-order derivatives. I can assure you that, you will be amazed after watching the results. So without any further due, let’s dive into it.

# Let’s do it…

## Step 1 — Let’s import the required packages.

`import cv2import matplotlib.pyplot as plt`

## Step 2 — Let's read the image.

`imgpath = "test.tiff"img = cv2.imread(imgpath, 1)img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)`

## Step 3 — Lets find the edges using Sobel X and Sobel Y in cv2.

Syntax cv2.Sobel(src, ddepth, dx, dy[, ksize[, scale[, delta[, borderType]]]]])

`edgesx = cv2.Sobel(img, -1, dx=1, dy=0, ksize=1)edgesy = cv2.Sobel(img, -1, dx=0, dy=1, ksize=1)`
• Sobel X simply finds the first-order derivative in the X-direction. It means that it will detect only those edges which are changing in the X direction (see 1st image).
• Similarly, Sobel Y finds the first-order derivative in the Y direction. It means that it will detect only those edges which are changing in the Y direction (see 2nd image).

Read my blog on second-order derivative: HOW TO DETECT EDGES USING LAPLACIAN 2ND ORDER DERIVATIVE IN PYTHON USING OPENCV

## Step 4 — Let’s merge these results of Sobel X and Sobel Y in cv2.

`edges = edgesx + edgesy`
• We can simply add edges in the X direction and edges in the Y direction to get the overall edges in our image (see final image).

## Step 5 — Plot the results.

`output = [img, edgesx, edgesy, edges]titles = ['Original', 'x', 'y', 'Edges']for i in range(4):    plt.subplot(2, 2, i + 1)    plt.imshow(output[i], cmap='gray')    plt.title(titles[i])    plt.xticks([])    plt.yticks([])plt.show()`

Do let me know if there’s any query regarding Sobel X and Sobel Y in cv2 by contacting me on email or LinkedIn.

For further code explanation and source code visit here https://machinelearningprojects.net/sobel-x-and-sobel-y-in-cv2/

So this is all for this blog folks, thanks for reading it and I hope you are taking something with you after reading this and till the next time …

Read my previous post: ROTATING AND SCALING IMAGES — A FUN APPLICATION IN PYTHON USING OPENCV

--

--

## More from MLearning.ai

Data Scientists must think like an artist when finding a solution when creating a piece of code. ⚪️ Artists enjoy working on interesting problems, even if there is no obvious answer ⚪️ linktr.ee/mlearning 🔵 Follow to join our 28K+ Unique DAILY Readers 🟠