Skip to content

Commit 18a980a

Browse files
authored
Create Cartoonize_An_Image.py
1 parent b6e927d commit 18a980a

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

Cartoonize_An_Image.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import cv2
2+
3+
num_down = 2
4+
# number of downsampling steps
5+
6+
num_bilateral = 7 # number of bilateral filtering steps
7+
8+
img_rgb = cv2.imread("myCat.jpg")
9+
10+
# downsample image using Gaussian pyramid
11+
12+
img_color = img_rgb
13+
14+
for _ in range(num_down):
15+
16+
img_color = cv2.pyrDown(img_color)
17+
18+
# repeatedly apply small bilateral filter instead of
19+
20+
# applying one large filter
21+
22+
for _ in range(num_bilateral):
23+
24+
img_color = cv2.bilateralFilter(img_color, d=9, sigmaColor=9, sigmaSpace=7)
25+
26+
# upsample image to original size
27+
28+
for _ in range(num_down):
29+
30+
img_color = cv2.pyrUp(img_color)
31+
32+
#STEP 2 & 3
33+
34+
#Use median filter to reduce noise
35+
36+
# convert to grayscale and apply median blur
37+
38+
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
39+
40+
img_blur = cv2.medianBlur(img_gray, 7)
41+
42+
#STEP 4
43+
44+
#Use adaptive thresholding to create an edge mask
45+
46+
# detect and enhance edges
47+
48+
img_edge = cv2.adaptiveThreshold(img_blur, 255,
49+
50+
cv2.ADAPTIVE_THRESH_MEAN_C,
51+
52+
cv2.THRESH_BINARY,
53+
54+
blockSize=9,
55+
56+
C=2)
57+
58+
# Step 5
59+
60+
# Combine color image with edge mask & display picture
61+
62+
# convert back to color, bit-AND with color image
63+
64+
img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB)
65+
66+
img_cartoon = cv2.bitwise_and(img_color, img_edge)
67+
68+
# display
69+
70+
cv2.imshow("myCat_cartoon", img_cartoon)

0 commit comments

Comments
 (0)