Converting An Image To A Cartoon Using OpenCV
Computer vision is one of the hottest fields in Artificial Intelligence with a wide variety of applications. OpenCV is the most popular library used in computer vision with a lot of interesting stuff. If you want to start your journey in computer vision you can start from learning OpenCV. It is easy to understand and implement by everyone. In this article using OpenCV, let’s have fun with converting normal images into cartoons.
We will cover the following steps in this article to convert the image to cartoon:-
- Importing libraries
- Defining the function
- Smoothing image
- Converting into greyscale & applying the medium blur
- Detect and enhance edges
- Again converting back to color
Now, let us proceed step-by-step.
Step-1: Here we are importing the required libraries. If you are working in Google Colab then we need to import google.colab.patches.
import cv2
import os
from google.colab.patches import cv2_imshow
Step-2: Here we are creating our own cartoonify function and assigning the required parameters.
def cartoonify(img_rgb):
numBilateralFilters = 4
img_color = img_rgb
cv2_imshow("/content/Screenshot (286).png")
Step-3: Here we are using BilateralFilter for smoothing images and we can make changes in our parameters. The higher values give a higher smoothing effect on the image.
for _ in range(numBilateralFilters):
img_color = cv2.bilateralFilter(img_color, 15, 30, 20)
cv2_imshow(img_color)
Step-4: Here we are converting the color image into greyscale and applying a blur to the grayscale image which adds a cartoony effect to the image and we are using a 7X7 blur filter.
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
img_blur = cv2.medianBlur(img_gray, 7)
cv2_imshow(img_blur)
Step-5: Here we are using the adaptive threshold function to extract the edges from the image.
img_edge = cv2.adaptiveThreshold(img_blur, 2,cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY, 3, 2)
cv2_imshow(img_edge)
Step-6: In the below code snippet, we are displaying the output.
img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB)
return cv2.bitwise_and(img_color, img_edge)
real_inputs = []
cartoon_outputs = []
img_rgb = cv2.imread("image.png")
output = cartoonify(img_rgb)
real_inputs.append(img_rgb)
cartoon_outputs.append(output)
cv2_imshow(output)
The transformation from input to output
Conclusion
In the above demonstration, we converted a normal image into a cartoon by implementing a few lines of code using computer vision techniques. we shall have great fun using computer vision techniques.
The post Converting An Image To A Cartoon Using OpenCV appeared first on Analytics India Magazine.




