Coders Packet

Cartoon Image Converter In Python

By Payal Nagar

This project transforms a photo into a cartoon-style image using OpenCV, preserving colors and highlighting edges for a unique artistic effect.

This Python code transforms an input image into a cartoon-like image using OpenCV. Here's a description of the code's steps:

Image Loading:

The code loads an image from the specified file path using cv2.imread and assigns it to the img variable.
Grayscale Conversion:

The image is converted to grayscale using cv2.cvtColor with the cv2.COLOR_BGR2GRAY conversion code.
Median Blur:

A median blur is applied to the grayscale image using cv2.medianBlur. This helps reduce noise in the image and creates a smoother appearance.
Edge Detection:

The adaptive thresholding method (cv2.adaptiveThreshold) is used to detect edges in the grayscale image. This process creates a binary image (edges) where edges are highlighted. It adapts the threshold for each pixel based on the local neighborhood's mean value.
Color Preservation:

A bilateral filter (cv2.bilateralFilter) is applied to the original color image (img) to preserve its color information while reducing noise. This filter smoothens the image while keeping the edges sharp.
Cartoon Effect:

The cartoon effect is achieved by applying a bitwise AND operation (cv2.bitwise_and) between the filtered color image (color) and the edge-detected binary image (edges). This operation retains the color of the original image in regions where edges are detected and turns other regions black.

code
Displaying Images:

The code displays three windows:
The original image (img) is in a window titled "Image."
The edge-detected image (edges) in a window titled "edges."
The cartoon-like image (cartoon) in a window titled "Cartoon."
User Interaction:

The program waits indefinitely (cv2.waitKey(0)) for a key press. When any key is pressed, the code proceeds to the next step.

output
Closing Windows:

After the user interaction, the code calls cv2.destroyAllWindows() to close all open OpenCV windows.
In summary, this code takes an input image and applies grayscale conversion, median blur, edge detection, and bilateral filtering to create a cartoon-like effect while preserving color details. It then displays the original image, the edge-detected image, and the cartoonized image in separate windows.

Download Complete Code

Comments

No comments yet

Download Packet

Reviews Report

Submitted by Payal Nagar (Payal)

Download packets of source code on Coders Packet