Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Maheshwari Thakur

Currently there are lots of professional cartoonizer applications available in the market but most of the them are not freeware. In order to get the basic cartoon effect, we just need the bilateral filter and some edge dectection mechanism. The bilateral filter will reduce the color palette, which is essential for the cartoon look and edge detection is to produce bold silhouettes.

We are going to use openCV python library to convert an RGB color image to a cartoon image.

Algorithm

  • Firstly apply the bilateral filter to reduce the color palette of the image.

  • Then conver the actual image to grayscale.

  • Now apply the median blur to reduce image noise in the grayscale image.

  • Create an edge mask from the grayscale image using adaptive thresholding.

  • Finally combine the color image produced from step 1 with edge mask produced from step 4.

Original Image

Example

#step 1
#Use bilateral filter for edge-aware smoothing.
import cv2

num_down = 2 # number of downsampling steps
num_bilateral = 7 # number of bilateral filtering steps

img_rgb = cv2.imread("myCat.jpg")

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

# repeatedly apply small bilateral filter instead of
# applying one large filter
for _ in range(num_bilateral):
img_color = cv2.bilateralFilter(img_color, d=9, sigmaColor=9, sigmaSpace=7)

# upsample image to original size
for _ in range(num_down):
   img_color = cv2.pyrUp(img_color)

#STEP 2 & 3
#Use median filter to reduce noise
# convert to grayscale and apply median blur
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
img_blur = cv2.medianBlur(img_gray, 7)

#STEP 4
#Use adaptive thresholding to create an edge mask
# detect and enhance edges
img_edge = cv2.adaptiveThreshold(img_blur, 255,
   cv2.ADAPTIVE_THRESH_MEAN_C,
   cv2.THRESH_BINARY,
   blockSize=9,
   C=2)

# Step 5
# Combine color image with edge mask & display picture
# convert back to color, bit-AND with color image
img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB)
img_cartoon = cv2.bitwise_and(img_color, img_edge)

# display
cv2.imshow("myCat_cartoon", img_cartoon)

Result

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.