tori29umai commited on
Commit
0a3b739
โ€ข
1 Parent(s): 906508c

Update utils/image_utils.py

Browse files
Files changed (1) hide show
  1. utils/image_utils.py +17 -5
utils/image_utils.py CHANGED
@@ -5,18 +5,30 @@ 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
- result = remove(input_image)
 
 
 
 
 
 
 
 
 
 
 
 
18
  result_path = "tmp.png"
19
- result.save(result_path)
20
 
21
  return result_path
22
 
 
5
 
6
  def background_removal(input_image_path):
7
  """
8
+ ๆŒ‡ๅฎšใ•ใ‚ŒใŸ็”ปๅƒใ‹ใ‚‰่ƒŒๆ™ฏใ‚’้™คๅŽปใ—ใ€็™ฝไปฅๅค–ใฎ้ ˜ๅŸŸใงใƒˆใƒชใƒŸใƒณใ‚ฐใ—ใŸ็”ปๅƒใ‚’่ฟ”ใ™้–ขๆ•ฐ
9
  """
10
  try:
11
+ input_image = Image.open(input_image_path).convert("RGB")
12
  except IOError:
13
  print(f"Error: Cannot open {input_image_path}")
14
  return None
15
 
16
+ # ่ƒŒๆ™ฏ้™คๅŽปๅ‡ฆ็† (็™ฝ่ƒŒๆ™ฏใฎRGB็”ปๅƒใจใ—ใฆ่ฟ”ใ•ใ‚Œใ‚‹)
17
+ result_image = remove(input_image).convert("RGB")
18
+
19
+ # ใƒˆใƒชใƒŸใƒณใ‚ฐๅ‡ฆ็†
20
+ bg = Image.new("RGB", result_image.size, (255, 255, 255)) # ็™ฝ่ƒŒๆ™ฏ
21
+ diff = ImageChops.difference(result_image, bg)
22
+ bbox = diff.getbbox() # ็™ฝไปฅๅค–ใฎ้ƒจๅˆ†ใ‚’ๅซใ‚€ๅขƒ็•Œใƒœใƒƒใ‚ฏใ‚นใ‚’ๅ–ๅพ—
23
+
24
+ if bbox:
25
+ cropped_image = result_image.crop(bbox)
26
+ else:
27
+ cropped_image = result_image # ๅ…จ้ƒจใŒ็™ฝใฎๅ ดๅˆใฏใใฎใพใพ่ฟ”ใ™
28
+
29
+ # ็ตๆžœใ‚’ไฟๅญ˜
30
  result_path = "tmp.png"
31
+ cropped_image.save(result_path)
32
 
33
  return result_path
34