After completing this lab, you will be able to:
- Convert colored images to grayscale
- Apply the Gaussian filter to smooth an image
- Detect the edges of an image using the Gradient Magnitude
- Convert a grayscale image to a binary image
- Create a pencil sketch of an image in OpenCV
- Create a water painting of an image in OpenCV
Get ready to start!
- Exercise 1: Import Libraries and Load your Images
- Exercise 2: Turning a Photograph into a Sketch
- Exercise 3: Pencil Sketch Effect
- Exercise 4: Water Color Painting Effect
- Exercise 5: Experiment With Your Own Photos!
- Exercise 6: Practice!
import requests
import os
# Make a folder to hold our images called "images" if it doesn't already exist
!mkdir -p ./images
# To add the image we will be using to this lab to the folder
if not os.path.isfile("./images/LandscapePhotograph.jpeg"):
r = requests.get("https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/transform-photos-to-sketches-and-paintings-with-opencv/images/LandscapePhotograph.jpeg")
f = open("./images/LandscapePhotograph.jpeg", mode = "wb+")
f.write(r.content)
f.close()
The edges of an image are the parts of an image where the brightness changes quickly. To detect the edges of an image, we need to compute something called the gradient magnitude of an image. The gradient magnitude of an image measures how quickly the image is changing and it is used for edge detection. To get a sketch for our photograph, we will compute the gradient magnitude of the image.
To get the gradient magnitude of an image, we need to calculate the verticle and horizontal components of the gradient of the image. In other words, we need to calculate how much the image changes in the horizontal direction (the x component of the gradient),
The formula for the gradient magnitude is
sobelx = cv2.Sobel(blur,cv2.CV_64F,1,0,ksize=5) # Change in horizonal direction, dx
sobely = cv2.Sobel(blur,cv2.CV_64F,0,1,ksize=5) # Change in verticle direction, dy
gradmag_sq = np.square(sobelx)+np.square(sobely) # Square the images element-wise and then add them together
gradmag = np.sqrt(gradmag_sq) # Take the square root of the resulting image element-wise to get the gradient magnitude
plt.imshow(gradmag, cmap ='gray')
Date (YYYY-MM-DD) | Version | Changed By | Change Description |
---|---|---|---|
2021-08-06 | 0.1 | Yasmine | Initial Version Created |
© IBM Corporation 2021. All rights reserved.