How to do it...

Perform the following steps:

  1. Import the packages:
import cv2import numpy as npimport matplotlib.pyplot as plt
  1. Read the image as grayscale:
image = cv2.imread('../data/Lena.png', 0)
  1. Compute the gradient approximations using the Sobel operator:
dx = cv2.Sobel(image, cv2.CV_32F, 1, 0)dy = cv2.Sobel(image, cv2.CV_32F, 0, 1)
  1. Visualize the results:
plt.figure(figsize=(8,3))plt.subplot(131)plt.axis('off')plt.title('image')plt.imshow(image, cmap='gray')plt.subplot(132)plt.axis('off')plt.imshow(dx, cmap='gray')plt.title(r'$\frac{dI}{dx}$')plt.subplot(133)plt.axis('off')plt.title(r'$\frac{dI}{dy}$')plt.imshow(dy, cmap='gray')plt.tight_layout()plt.show()

Get OpenCV 3 Computer Vision with Python Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.