Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python to convert selfie into cartoon style

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "how to use Python to convert selfie into cartoon style". In daily operation, I believe many people have doubts about how to use Python to convert selfie into cartoon style. I have consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use Python to convert selfie into cartoon style". Next, please follow the editor to study!

Nowadays, sketching or creating cartoons doesn't have to be done manually, and many apps can convert your photos into cartoons. It's not as difficult as you think, and it only takes a few lines of code to achieve the desired effect.

There is a library called OpenCV, which provides a general infrastructure for computer vision applications and optimizes machine learning algorithms. It can be used to identify objects, detect and generate high-resolution images. This tutorial will show you how to use OpenCV to give cartoon effects to images in Python. Google Colab will be used in the tutorial to write and run the code.

To create a cartoon effect, you need to pay attention to two things: edges and color palettes. This is the difference between photos and cartoon pictures. To adjust these two points, you will go through four main steps:

Load Ima

Create an edge mask

Reduce color palettes

Combine an edge mask with a color-processed image

Before you begin, don't forget to import the required libraries in your notebook, especially cv2 and NumPy.

Defread_file (filename): img = cv2.imread (filename) cv2_imshow (img) return img

1. Load Ima

The first step is to load the picture. Define the read_file function, which contains cv2_imshow, to load the image we selected in Google Colab.

Defread_file (filename): img = cv2.imread (filename) cv2_imshow (img) return img

Call the created function to load the image:

Uploaded = files.upload () filename = next (iter (uploaded)) img = read_file (filename)

I chose to turn the following picture into a cartoon picture:

two。 Create an edge mask

Common cartoon effects emphasize the thickness of the edges in the image. You can use the cv2.adaptiveThreshold () function to detect edges in an image. We can define the egde_mask function as:

Defedge_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

In this function, we convert the image into a grayscale image, and then use cv2.medianBlur to reduce the noise of the blurred grayscale image. The higher the blur value, the less black noise in the image. Then, the adaptiveThreshold function is applied to define the line thickness of the edge. The thicker the lines, the thicker the highlighted edges in the image.

After defining the function, you can see the result by calling the function.

Line_size = 7 blur_value = 7edges = edge_mask (img, line_size, blur_value) cv2_imshow (edges)

Edge mask detection

3. Reduce color palettes

In terms of color, the main difference between photos and sketches is their respective number of colors. Sketches have fewer colors than photos. Therefore, we use color quantization to reduce the number of colors in the photo.

To quantify the color, we use the K-means clustering algorithm provided by the OpenCV library. To make it easier to use in the next steps, you can define the color_quantization function as follows:

Defcolor_quantization (img, k): # Transform theimage data = np.float32 (img). Reshape ((- 1,3)) # Determinecriteria criteria = (cv2.TERM_CRITERIA_EPS+ cv2.TERM_CRITERIA_MAX_ITER, 20 0.001) # ImplementingK-Means ret, label, center = cv2.kmeans (data, k, None, criteria, 10 Cv2.KMEANS_RANDOM_CENTERS) center = np.uint8 (center) result = center [label.flatten ()] resultresult = result.reshape (img.shape) return result

You can adjust the k value to determine the number of colors you want to apply to the image:

Total_color = 9 img = color_quantization (img, total_color)

In this example, the k value of the image is set to 9. The results are as follows:

After color quantization

After the color quantization is completed, the noise in the image can be reduced by bilateral filtering. This makes the image slightly blurred and less sharp.

Blurred = cv2.bilateralFilter (img, dong7, sigmaColor=200,sigmaSpace=200)

Here are three parameters that you can adjust according to your preferences.

D-the diameter of each pixel's neighborhood.

SigmaColor-the higher the value of this parameter, the larger the semi-isochromatic area.

SigmaSpace-the higher the value of this parameter, means that distant pixels will affect each other as long as their colors are close enough.

After using bilateral filtering

4. Combine an edge mask with a color-processed image

The final step is to combine the edge mask we created earlier with the color-processed image. To do this, you need to use the cv2.bitwise_and function.

Cartoon = cv2.bitwise_and (blurred, blurred, mask=edges)

This is the "cartoon version" of the original picture:

Final effect

Now you can start to create your own cartoon effects. In addition to adjusting the parameter values we used above, you can add another function from OpenCV to add special effects to your photos, and there is a lot to explore in the library. Have a good try!

At this point, the study on "how to convert a selfie into a cartoon style with Python" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report