Book Image

OpenCV with Python By Example

By : Prateek Joshi
Book Image

OpenCV with Python By Example

By: Prateek Joshi

Overview of this book

Table of Contents (19 chapters)
OpenCV with Python By Example
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Cartoonizing an image


Now that we know how to handle the webcam and keyboard/mouse inputs, let's go ahead and see how to convert a picture into a cartoon-like image. We can either convert an image into a sketch or a colored cartoon image.

Following is an example of what a sketch will look like:

If you apply the cartoonizing effect to the color image, it will look something like this next image:

Let's see how to achieve this:

import cv2
import numpy as np

def cartoonize_image(img, ds_factor=4, sketch_mode=False):
    # Convert image to grayscale
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Apply median filter to the grayscale image
    img_gray = cv2.medianBlur(img_gray, 7)

    # Detect edges in the image and threshold it
    edges = cv2.Laplacian(img_gray, cv2.CV_8U, ksize=5)
    ret, mask = cv2.threshold(edges, 100, 255, cv2.THRESH_BINARY_INV)

    # 'mask' is the sketch of the image
    if sketch_mode:
        return cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)

    # Resize the...