Let’s get into the code now.
- For the first step, let us import the required libraries as below
import cv2
import numpy as np - For the second step, let us read an image as input
img = cv2.imread(“my_image.jpg”)
Here my image name in my_image.jpg - For the third step, let us get the edges of the image read as input
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
In the above step, we converted the normal BGR image to Grayscale and applied median blurring on the image. Post that apply the adaptiveThreshold on the image which will yield the image containing all the edges.
gray = cv2.medianBlur(gray, 5)
edges = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 9)
4. For the fourth step, let us cartoonize the image using the bitwise and of the color generated images using bilateral filter. Let us see the code to do this.color = cv2.bilateralFilter(img, 9, 250, 250)
cartoon = cv2.bitwise_and(color, color, mask=edges)
5. For the final step, we will visualize our results using the below codecv2.imshow(“Image”, img)
cv2.imshow(“Edges”, edges)
cv2.imshow(“Cartoon”, cartoon)
6. Always remember to use waitKey and destroy the windows before exiting, hence use the below code.cv2.waitKey(0)
cv2.destroyAllWindows()
Credit: BecomingHuman By: Akash Bhiwgade