-
Notifications
You must be signed in to change notification settings - Fork 5
/
pyblur.py
42 lines (38 loc) · 1.67 KB
/
pyblur.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
import cv2
import numpy as np
def SoftBlurContours(image, contours, ksize, sigmaX, *args, **kwargs):
iterations = 3
if 'iters' in kwargs:
iterations = kwargs['iters']
sigmaY = args[0] if len(args) > 0 and args[0] != None else sigmaX
mksize = args[1] if len(args) > 1 and args[1] != None else ksize
msigmaX = args[2] if len(args) > 2 and args[2] != None else sigmaX
msigmaY = args[3] if len(args) > 3 and args[3] != None else msigmaX
mask = np.zeros(image.shape[:2])
for i, contour in enumerate(contours):
cv2.drawContours(mask, contour, 0, 255, -1)
blurred_image = cv2.GaussianBlur(image, (ksize,ksize), sigmaX, None, sigmaY)
result = np.copy(image)
for _ in xrange(iterations):
alpha = mask/255.
result = alpha[:, :, None]*blurred_image + (1-alpha)[:, :, None]*result
mask = cv2.GaussianBlur(mask, (mksize, mksize), msigmaX, None, msigmaY)
return result
def SoftBlurRect(image, rect, ksize, sigmaX, *args, **kwargs):
x,y,w,h = rect
contours = [[np.array([[x,y],[x+w,y],[x+w,y+h],[x,y+h]])]]
return SoftBlurContours(image, contours, ksize, sigmaX, *args, **kwargs)
def BlurContours(image, contours, ksize, sigmaX, *args):
sigmaY = args[0] if len(args) > 0 else sigmaX
mask = np.zeros(image.shape[:2])
for i, contour in enumerate(contours):
cv2.drawContours(mask, contour, i, 255, -1)
blurred_image = cv2.GaussianBlur(image, (ksize, ksize), sigmaX, None, sigmaY)
result = np.copy(image)
alpha = mask/255.
result = alpha[:, :, None]*blurred_image + (1-alpha)[:, :, None]*result
return result
def BlurRect(image, rect, ksize, sigmaX, *args):
x,y,w,h = rect
contours = [[np.array([[x,y],[x+w,y],[x+w,y+h],[x,y+h]])]]
return BlurContours(image, contours, ksize, sigmaX, *args)