【Image Processing】Use OpenCV to turn your photos into cartoons

image to cartoon

1. Description

        In today's world, we are surrounded by images and videos. From social media to advertising, images have become a powerful medium of communication. But have you ever wondered what would happen if you could turn your photos into cartoons? Imagine creating animated versions of your favorite photos, or transforming portraits into whimsical illustrations.

        In this article, we'll explore how to convert an image into a cartoon using the OpenCV library in Python. OpenCV is a powerful computer vision library that provides a wide range of functions for image and video processing, including edge detection, color conversion, and filtering. We will use these tools to create a cartoon effect on a given image.

        To do this, we will first import the necessary modules and load the input image. Next, we'll apply a series of transformations to the image, including edge detection, color quantization, and bilateral filtering. Finally, we will combine these transformations to create a cartoon effect on the input image. Throughout this article, we will provide step-by-step instructions on how to implement each conversion using OpenCV. By the end of this article, you will have a clear understanding of how to use OpenCV to create a cartoon effect on any input image. So let's dive into how to convert an image into a cartoon using OpenCV!

2. Import the necessary libraries 

import cv2
import numpy as np
import os

2.1 Code description:

  • import cv2Imports the OpenCV library, which provides extensive functionality for image and video processing.
  • import numpy as npImport the NumPy library, a popular library for working with arrays and matrices in Python.
  • import osImports the operating system module, which provides a way to interact with the file system.

In summary, this code imports the necessary modules to perform image processing using OpenCV in Python.

2.2 Display the input image using OpenCV in Python:

img = cv2.imread('original_picture.jpg')
cv2.imshow("original", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Original Image

2.3 Code description:

  • cv2.imread('original_picture.jpg')Load the input image named "original_picture.jpg" into a variable named . This is the name of the picture you want.img
  • cv2.imshow("original", img) Display the input image in a window titled "Original".
  • cv2.waitKey(0)Waiting for a keypress. An argument of 0 means the program will wait indefinitely until a key is pressed.
  • cv2.destroyAllWindows() Close all open windows.

3. Use K-means clustering for color quantization:

def color_quantization(img, k):
# Transform the image
  data = np.float32(img).reshape((-1, 3))

# Determine criteria
  criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 0.001)

# Implementing K-Means
  ret, label, center = cv2.kmeans(data, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
  center = np.uint8(center)
  result = center[label.flatten()]
  result = result.reshape(img.shape)
  return result

3.1 Function description:

  • The function takes two parameters — the input image and the number of clusters.imgk
  • The input image is first converted to a two-dimensional array of pixel values ​​using the NumPy library.
  • Determines a set of conditions for the K-Means clustering algorithm, including the maximum number of iterations and minimum change in cluster centers.
  • The K-means cluster analysis algorithm is applied to the data using the cv2.kmeans() function, with a specified number of clusters and conditions. If the variable changes, the function will generate a new quantized image with a different number of color clusters. Smaller values ​​will result in a quantized image with fewer colors, while larger values ​​will result in a quantized image with more colors.kkk
  • The resulting cluster centers are converted to 8-bit integers using NumPy functions.np.uint8()
  • The original image is flattened into a 1D array of pixel values, and each pixel is assigned to its nearest cluster center.
  • The resulting array of pixel values ​​is then reshaped back to the shape of the original input image.
  • The resulting quantized image is returned as the output of the function.

3.2 Create an edge mask:

def edge_mask(img, line_size, blur_value):
  gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  gray_blur = cv2.medianBlur(gray, blur_value)
  edges = cv2.adaptiveThreshold(gray_blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, line_size, blur_value)
  return edges

3.3 Function description:

  • The function takes three parameters - the input image, the size of the lines in the mask, and the amount of blur to apply to the grayscale image. If the variable changes, the size of the lines in the mask changes accordingly. Smaller values ​​will result in thinner lines, while larger values ​​will result in thicker lines.imgline_sizeblur_valueline_size
  • First convert the input image to grayscale using this function.cv2.cvtColor()
  • Then use the with specified. If the variable changes, the blur level applied to the grayscale image will change. Smaller values ​​will result in less blur, while larger values ​​will result in more blur.cv2.medianBlur()blur_valueblur_value
  • Create an edge mask by using this function to apply an adaptive threshold to a blurred grayscale image. This adaptive thresholding method computes a threshold for each pixel based on the average of pixel values ​​in a local neighborhood around each pixel.cv2.adaptiveThreshold()
  • The resulting edge mask is returned as the output of the function.

Fourth, generate a pencil sketch from an image:

line_size = 7
blur_value = 7

edges = edge_mask(img, line_size, blur_value)
cv2.imwrite('pencil_sketch.jpg', edges)
cv2.imshow('pencil sketch', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()

pencil sketch

4.1 Code description:

  • The code first sets the value of sum to 7. If the values ​​of and are changed, the resulting pencil sketch will be affected. Smaller values ​​will result in thinner lines, while larger values ​​will result in thicker lines. Again, smaller values ​​will result in less blur, while larger values ​​will result in more blur, which may affect the overall appearance of the pencil sketch.line_sizeblur_valueline_sizeblur_valueline_sizeblur_value
  • Generates an edge mask from an input image using a function with the specified sum.imgedge_mask()line_sizeblur_value
  • The resulting edge mask is saved using this function as a new image file named "pencil_sketch.jpg".cv2.imwrite()
  • Then use this function to display the pencil sketch image.cv2.imshow()
  • The program waits for the user to press a key using this function.cv2.waitKey(0)
  • Finally, use the function to close all open windows.cv2.destroyAllWindows()

4.2 Generate cartoons from images:

total_color = 9
img = color_quantization(img, total_color)
cv2.imwrite('cartoonize.jpg', img)
cv2.imshow('Cartoonize', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Cartoon picture

4.3 Code description:

  • The code first sets the value to 9. If the value changes, the resulting cartoon image will be affected. Smaller values ​​will result in fewer colors, while larger values ​​will result in more colors, which may affect the overall look of the cartoon image.total_colortotal_colortotal_color
  • Call this function to reduce the number of colors in the input image to the specified one.color_quantization()imgtotal_color
  • The resulting image is saved as a new image file called "cartoonize.jpg" using this function.cv2.imwrite()
  • Then use that function to display a cartoon image.cv2.imshow()
  • The program waits for the user to press a key using this function.cv2.waitKey(0)
  • Finally, use the function to close all open windows.cv2.destroyAllWindows()

5. Apply a bilateral filter to the image:

bilateral = cv2.bilateralFilter(img, 15, 75, 75)
# Save the output.
cv2.imwrite('blur.jpg', bilateral)
img = cv2.imread('blur.jpg')
cv2.imshow("Blur", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

bilateral filtering

5.1 Code description:

  • The code first uses this function to apply a bilateral filter to the input image. The filter size is set to 15 and the values ​​of both sigma color and sigma space are set to 75.imgcv2.bilateralFilter()
  • Changing the values ​​of Kernel Size, Sigma Color, and Sigma Space for a bilateral filter will affect the level of blur applied to the image. Smaller kernel size and sigma values ​​will result in less blurring, while larger values ​​will result in more blurring. Changing these values ​​may change the overall appearance of the resulting blurred image.
  • The resulting blurred image is saved as a new image file called "blur.jpg", using this function.cv2.imwrite()
  • Then use that function to load the blurred image back into memory and assign to a variable.cv2.imread()img

5.2 Total output:

5.3 Another way:

import cv2
import numpy as np

# Load the input image
img = cv2.imread('input_image.jpg')

# Apply bilateral filter to smooth the image
img_smooth = cv2.bilateralFilter(img, 9, 75, 75)

# Convert the image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Apply edge detection to the grayscale image
edges = cv2.Canny(gray, 100, 200)

# Apply color quantization to the smoothed image
img_quant = cv2.cvtColor(img_smooth, cv2.COLOR_BGR2RGB)
Z = img_quant.reshape((-1,3))
Z = np.float32(Z)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 8
ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)
center = np.uint8(center)
res = center[label.flatten()]
res2 = res.reshape((img_quant.shape))

# Combine the edges and color quantization to create the cartoon effect
cartoon = cv2.bitwise_and(res2, res2, mask=edges)

# Display the output image and save it
cv2.imshow('Cartoon', cartoon)
cv2.waitKey(0)
cv2.destroyAllWindows()

        All in all, converting images to cartoons using OpenCV is a fun and creative way to give new life to your photos. In this article, we discussed how to use OpenCV to convert an image into a cartoon by applying various image processing techniques such as color quantization, edge detection, and bilateral filtering. By combining these techniques, we are able to produce stylized cartoon images from ordinary photos.

        While the code provided in this article is a good starting point, there are many ways to customize the conversion process to achieve different results. Experimenting with different parameter values ​​or applying other image processing techniques can help create unique and personalized cartoon-like images. With a little creativity and some knowledge of image manipulation techniques, the possibilities are endless.

Guess you like

Origin blog.csdn.net/gongdiwudu/article/details/131957541