Skip to content

Commit e30e72c

Browse files
authored
Update image_background_subtractor.py
1 parent 183e560 commit e30e72c

File tree

1 file changed

+5
-19
lines changed

1 file changed

+5
-19
lines changed
Lines changed: 5 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,18 @@
11
import cv2
22
import mediapipe as mp
33
import numpy as np
4-
from PIL import Image
5-
64
mp_drawing = mp.solutions.drawing_utils
75
mp_selfie_segmentation = mp.solutions.selfie_segmentation
8-
9-
IMAGE_FILES = ['location_to_image/image.jpg'] # You can use multiple Images for removal at a go by just specifying the name of the images in the list.
10-
BG_COLOR = (255, 255, 255) # White Background
6+
# You can use multiple Images for removal at a go by just specifying the name of the images in the list.
7+
IMAGE_FILES = ['location_to_image/image.jpg']
8+
BG_COLOR = (192, 192, 192) # gray, you can set to any
119
with mp_selfie_segmentation.SelfieSegmentation(model_selection=0) as selfie_segmentation:
1210
for idx, file in enumerate(IMAGE_FILES):
13-
image = cv2.imread(file, cv2.IMREAD_UNCHANGED)
11+
image = cv2.imread(file)
1412
image_height, image_width, _ = image.shape
1513
results = selfie_segmentation.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
1614
condition = np.stack((results.segmentation_mask,) * 3, axis=-1) > 0.1
1715
bg_image = np.zeros(image.shape, dtype=np.uint8)
1816
bg_image[:] = BG_COLOR
1917
output_image = np.where(condition, image, bg_image)
20-
cv2.imwrite('./white_bg' + str(idx) + '.png', output_image)
21-
# Converting the White Background to Transparent Background.
22-
img = Image.open("./white_bg"+str(idx)+".png")
23-
img = img.convert("RGBA")
24-
datas = img.getdata()
25-
newData = []
26-
for item in datas:
27-
if item[0] == 255 and item[1] == 255 and item[2] == 255:
28-
newData.append((255, 255, 255, 0))
29-
else:
30-
newData.append(item)
31-
img.putdata(newData)
32-
img.save("location_to_store_result/Result" + str(idx) + ".png", "PNG")
18+
cv2.imwrite('location_to_store_result/result' + str(idx) + '.png', output_image)

0 commit comments

Comments
 (0)