tori29umai commited on
Commit
0aa210d
·
verified ·
1 Parent(s): 05d9ddd

Update utils/image_utils.py

Browse files
Files changed (1) hide show
  1. utils/image_utils.py +22 -10
utils/image_utils.py CHANGED
@@ -3,16 +3,28 @@ import numpy as np
3
  import cv2
4
  from rembg import remove
5
 
6
- def remove_background(input_image):
7
- rgba_image = remove(input_image)
8
- # アルファチャネルをマスクとして使用
9
- alpha_channel = rgba_image[:, :, 3]
10
-
11
- # 白い背景画像を作成
12
- background = np.ones_like(rgba_image, dtype=np.uint8) * 255
13
- # マスクを適用
14
- background_masked = cv2.bitwise_and(background, background, mask=alpha_channel)
15
- return background_masked
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  def resize_image_aspect_ratio(image):
18
  # 元の画像サイズを取得
 
3
  import cv2
4
  from rembg import remove
5
 
6
+ def background_removal(input_image_path):
7
+ """
8
+ 指定された画像から背景を除去し、白背景に置き換えた画像を返す関数
9
+ """
10
+ try:
11
+ input_image = Image.open(input_image_path)
12
+ except IOError:
13
+ print(f"Error: Cannot open {input_image_path}")
14
+ return None
15
+
16
+ # 背景除去処理
17
+ rgba_image = remove(input_image).convert("RGBA")
18
+ rgba_np = np.array(rgba_image)
19
+ alpha_channel = rgba_np[:, :, 3]
20
+
21
+ # 白背景の生成と合成
22
+ background = np.ones_like(rgba_np[:, :, :3], dtype=np.uint8) * 255
23
+ foreground = cv2.bitwise_and(rgba_np[:, :, :3], rgba_np[:, :, :3], mask=alpha_channel)
24
+ background_masked = cv2.bitwise_and(background, background, mask=cv2.bitwise_not(alpha_channel))
25
+ result = cv2.add(foreground, background_masked)
26
+
27
+ return Image.fromarray(result)
28
 
29
  def resize_image_aspect_ratio(image):
30
  # 元の画像サイズを取得