-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathsketch_filter.py
66 lines (56 loc) · 1.98 KB
/
sketch_filter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import cv2
class Sketcher(object):
"""Sketch Filter
A class that applies Sketch filter to an image.
The class uses a bilateral filter and adaptive thresholding to create
a sketch.
"""
def __init__(self):
pass
def resize(self,image,window_height = 500):
aspect_ratio = float(image.shape[1])/float(image.shape[0])
window_width = window_height/aspect_ratio
image = cv2.resize(image, (int(window_height),int(window_width)))
return image
def render(self, img_rgb):
img_rgb = cv2.imread(img_rgb)
img_rgb = self.resize(img_rgb, 500)
numDownSamples = 2 # number of downscaling steps
numBilateralFilters = 50 # number of bilateral filtering steps
# -- STEP 1 --
# downsample image using Gaussian pyramid
img_color = img_rgb
for _ in range(numDownSamples):
img_color = cv2.pyrDown(img_color)
# repeatedly apply small bilateral filter instead of applying
# one large filter
for _ in range(numBilateralFilters):
img_color = cv2.bilateralFilter(img_color, 9, 9, 7)
# upsample image to original size
for _ in range(numDownSamples):
img_color = cv2.pyrUp(img_color)
# -- STEPS 2 and 3 --
# convert to grayscale and apply median blur
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
img_blur = cv2.medianBlur(img_gray, 3)
# -- STEP 4 --
# detect and enhance edges
img_edge = cv2.adaptiveThreshold(img_blur, 255,
cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY,9, 2)
# -- STEP 5 --
# convert back to color
(x,y,z) = img_color.shape
img_edge = cv2.resize(img_edge,(y,x))
img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB)
#cv2.imwrite("edge.png",img_edge)
return img_edge
def start(self, img_path):
tmp_canvas = Sketcher() #make a temporary object
file_name = img_path #File_name will come here
res = tmp_canvas.render(file_name)
cv2.imwrite("Sketch version.jpg", res)
cv2.imshow("Sketch version", res)
cv2.waitKey(0)
cv2.destroyAllWindows()
print("Image saved as 'Sketch version.jpg'")