Cartoonizing an Image Using OpenCV and Python

Computer vision is an incredibly powerful tool with limitless possibilities. This allows for a variety of creative and practical applications. If you want to create cartoon-style images from regular images without manual painting or drawing, OpenCV, a popular computer vision library in Python, can help you achieve impressive results with little effort.

In this guide, we’ll walk you through a project that uses Python to turn an image into a cartoon-style image using OpenCV. This technique uses a set of image filters, transformations, and edge detection techniques to create the final cartoon effect. Let’s take a look at the details!

What is Cartoonizing an Image?

When creating cartoon images You can use many filters and image processing techniques to create funny or cartoon-like images. In this project we will use Python and OpenCV to:

  • Reduce the image size and use a double-sided filter.
  • Blurred grayscale version of the image.
  • Find the edges and overlay them on the colored image to create a cartoon effect.

Installing Dependencies

Before starting, make sure you have opencv-python installed. Run the following command in your terminal:

Bash
pip install opencv-python

Step-by-Step Code Explanation

Below is the step-by-step breakdown of the code to cartoonize an image:

Step 1: Import Libraries

Import the necessary libraries for image processing:

Python
import cv2
from google.colab.patches import cv2_imshow  # For displaying images in Google Colab

Step 2: Create the Cartoonizer Class

To structure the cartoon effect code, we’ll create a class called Cartoonizer:

Python
class Cartoonizer:
    """Cartoonizer effect: A class that applies a cartoon effect to an image."""
    def __init__(self):
        pass

    def render(self, img_rgb):
        img_rgb = cv2.imread(img_rgb)  # Load the image
        img_rgb = cv2.resize(img_rgb, (1366, 768))  # Resize the image
        numDownSamples = 2  # Downscale the image
        numBilateralFilters = 50  # Bilateral filter applications

        # Downsample image using Gaussian pyramid
        img_color = img_rgb
        for _ in range(numDownSamples):
            img_color = cv2.pyrDown(img_color)

        # Apply bilateral filters
        for _ in range(numBilateralFilters):
            img_color = cv2.bilateralFilter(img_color, 9, 9, 7)

        # Upscale image back to original size
        for _ in range(numDownSamples):
            img_color = cv2.pyrUp(img_color)

        # Convert to grayscale and apply median blur
        img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
        img_blur = cv2.medianBlur(img_gray, 3)

        # Edge detection using adaptive thresholding
        img_edge = cv2.adaptiveThreshold(img_blur, 255,
                                         cv2.ADAPTIVE_THRESH_MEAN_C,
                                         cv2.THRESH_BINARY, 9, 2)

        # Resize and convert edges back to color
        img_edge = cv2.resize(img_edge, (img_color.shape[1], img_color.shape[0]))
        img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB)

        # Combine edge mask with the color image
        return cv2.bitwise_and(img_color, img_edge)

Step 3: Applying the Cartoon Effect

Use the Cartoonizer class to apply the cartoon effect to your chosen image:

Python
tmp_canvas = Cartoonizer()
file_name = "Screenshot.png"  # Replace with the path to your image
res = tmp_canvas.render(file_name)

# Save and display the cartoon version
cv2.imwrite("Cartoon_Version.jpg", res)
cv2_imshow(res)
cv2.waitKey(0)
cv2.destroyAllWindows()

Simpler Implementation

If you want a more concise approach, here’s a simplified version using fewer steps:

Python
import cv2
from google.colab.patches import cv2_imshow

# Load the image
img = cv2.imread("Screenshot.png")  # Make sure the file path is correct

# Verify the image loaded correctly
if img is None:
    print("Error: Could not load image. Please check the file path.")
else:
    # Edge detection
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray = cv2.medianBlur(gray, 5)
    edges = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
                                  cv2.THRESH_BINARY, 9, 9)

    # Apply cartoon effect
    color = cv2.bilateralFilter(img, 9, 250, 250)
    cartoon = cv2.bitwise_and(color, color, mask=edges)

    # Display results
    cv2_imshow(img)
    cv2_imshow(edges)
    cv2_imshow(cartoon)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

Experiment and Explore

This method is a general guideline for creating cartoon images. But you need to adjust the parameters to get the best results for different images:

  • A multi-step sampling procedure was used.
  • Adjust the double-sided filter parameters to make the cartoon effect sharper or softer.
  • Try different edge detection methods such as Canny or other thresholding techniques.
  • Test various pore sizes To control the smoothness and sharpness of the edges

Share This Post:

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top