|
1 | 1 | import cv2
|
2 | 2 | import mediapipe as mp
|
3 | 3 | import numpy as np
|
4 |
| -from PIL import Image |
5 |
| - |
6 | 4 | mp_drawing = mp.solutions.drawing_utils
|
7 | 5 | 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 |
11 | 9 | with mp_selfie_segmentation.SelfieSegmentation(model_selection=0) as selfie_segmentation:
|
12 | 10 | for idx, file in enumerate(IMAGE_FILES):
|
13 |
| - image = cv2.imread(file, cv2.IMREAD_UNCHANGED) |
| 11 | + image = cv2.imread(file) |
14 | 12 | image_height, image_width, _ = image.shape
|
15 | 13 | results = selfie_segmentation.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
|
16 | 14 | condition = np.stack((results.segmentation_mask,) * 3, axis=-1) > 0.1
|
17 | 15 | bg_image = np.zeros(image.shape, dtype=np.uint8)
|
18 | 16 | bg_image[:] = BG_COLOR
|
19 | 17 | 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