Spaces:
Running
Running
Upload Blur.py
Browse files
Blur.py
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
from PIL import Image
|
3 |
+
import numpy as np
|
4 |
+
from rembg import remove
|
5 |
+
|
6 |
+
def cv_to_pil(img):
|
7 |
+
return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGRA2RGBA))
|
8 |
+
|
9 |
+
|
10 |
+
def pil_to_cv(img):
|
11 |
+
return cv2.cvtColor(np.array(img), cv2.COLOR_RGBA2BGRA)
|
12 |
+
|
13 |
+
|
14 |
+
def motion_blur(img, distance, amount):
|
15 |
+
# Convert to RGBA
|
16 |
+
img = img.convert('RGBA')
|
17 |
+
|
18 |
+
# Convert pil to cv
|
19 |
+
cv_img = pil_to_cv(img)
|
20 |
+
|
21 |
+
# Generating the kernel
|
22 |
+
kernel_motion_blur = np.zeros((distance, distance))
|
23 |
+
kernel_motion_blur[int((distance-1)/2), :] = np.ones(distance)
|
24 |
+
kernel_motion_blur = kernel_motion_blur / distance
|
25 |
+
|
26 |
+
# Applying the kernel to the input image
|
27 |
+
output = cv2.filter2D(cv_img, -1, kernel_motion_blur)
|
28 |
+
|
29 |
+
# Convert cv to pil
|
30 |
+
blur_img = cv_to_pil(output).convert('RGBA')
|
31 |
+
|
32 |
+
# Blend the original image and the blur image
|
33 |
+
final_img = Image.blend(img, blur_img, amount)
|
34 |
+
|
35 |
+
return final_img
|
36 |
+
|
37 |
+
|
38 |
+
def background_motion_blur(background, distance_blur, amount_blur, amount_subject):
|
39 |
+
# Remove background
|
40 |
+
subject = remove(background)
|
41 |
+
|
42 |
+
# Blur the background
|
43 |
+
background_blur = motion_blur(background, distance_blur, amount_blur)
|
44 |
+
|
45 |
+
# Put the subject on top of the blur background
|
46 |
+
subject_on_blur_background = Image.alpha_composite(background_blur, subject)
|
47 |
+
|
48 |
+
# Blend the subject and the blur background
|
49 |
+
result = Image.blend(background_blur, subject_on_blur_background, amount_subject)
|
50 |
+
|
51 |
+
return result
|