|
6 | 6 | mp_drawing = mp.solutions.drawing_utils
|
7 | 7 | mp_selfie_segmentation = mp.solutions.selfie_segmentation
|
8 | 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 |
| 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 |
11 | 11 | with mp_selfie_segmentation.SelfieSegmentation(model_selection=0) as selfie_segmentation:
|
12 | 12 | for idx, file in enumerate(IMAGE_FILES):
|
13 | 13 | image = cv2.imread(file, cv2.IMREAD_UNCHANGED)
|
14 | 14 | image_height, image_width, _ = image.shape
|
15 | 15 | results = selfie_segmentation.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
|
16 | 16 | condition = np.stack((results.segmentation_mask,) * 3, axis=-1) > 0.1
|
17 |
| - bg_image = np.zeros(image.shape,dtype=np.uint8) |
18 |
| - bg_image[:] = BG_COLOR |
19 |
| - output_image = np.where(condition,image,bg_image) |
| 17 | + bg_image = np.zeros(image.shape, dtype=np.uint8) |
| 18 | + bg_image[:] = BG_COLOR |
| 19 | + output_image = np.where(condition, image, bg_image) |
20 | 20 | cv2.imwrite('./white_bg' + str(idx) + '.png', output_image)
|
21 | 21 | # Converting the White Background to Transparent Background.
|
22 | 22 | img = Image.open("./white_bg"+str(idx)+".png")
|
23 |
| - img = img.convert("RGBA") |
| 23 | + img = img.convert("RGBA") |
24 | 24 | datas = img.getdata()
|
25 |
| - newData = [] |
| 25 | + newData = [] |
26 | 26 | for item in datas:
|
27 | 27 | if item[0] == 255 and item[1] == 255 and item[2] == 255:
|
28 | 28 | newData.append((255, 255, 255, 0))
|
29 | 29 | else:
|
30 | 30 | newData.append(item)
|
31 | 31 | img.putdata(newData)
|
32 |
| - img.save("location_to_store_result/Result"+ str(idx) +".png", "PNG") |
33 |
| - |
34 |
| - |
| 32 | + img.save("location_to_store_result/Result" + str(idx) + ".png", "PNG") |
0 commit comments