tori29umai commited on
Commit
16a8ae4
โ€ข
1 Parent(s): 62d9833

Update utils/image_utils.py

Browse files
Files changed (1) hide show
  1. utils/image_utils.py +12 -16
utils/image_utils.py CHANGED
@@ -1,35 +1,31 @@
1
- from PIL import Image, ImageChops
2
  import numpy as np
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).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
 
35
  def resize_image_aspect_ratio(image):
 
1
+ from PIL import Image
2
  import numpy as np
3
  import cv2
4
  from rembg import remove
5
 
6
  def background_removal(input_image_path):
7
  """
8
+ ๆŒ‡ๅฎšใ•ใ‚ŒใŸ็”ปๅƒใ‹ใ‚‰่ƒŒๆ™ฏใ‚’้™คๅŽปใ—ใ€้€ๆ˜Ž้ƒจๅˆ†ใ‚’็™ฝ่ƒŒๆ™ฏใซใƒ–ใƒฌใƒณใƒ‰ใ—ใฆ่ฟ”ใ™้–ขๆ•ฐใ€‚
9
+ ้€้Žใ•ใ‚Œใฆใ„ใชใ„้ƒจๅˆ†ใงใƒˆใƒชใƒŸใƒณใ‚ฐใ‚‚่กŒใ„ใพใ™ใ€‚
10
  """
11
  try:
12
+ input_image = Image.open(input_image_path).convert("RGBA")
13
  except IOError:
14
  print(f"Error: Cannot open {input_image_path}")
15
  return None
16
 
17
+ # ่ƒŒๆ™ฏ้™คๅŽปๅ‡ฆ็†
18
+ result = remove(input_image)
 
 
 
 
 
19
 
20
+ # ้€้Žใ•ใ‚Œใฆใ„ใชใ„้ƒจๅˆ†ใ‚’ใƒˆใƒชใƒŸใƒณใ‚ฐ
21
+ bbox = result.getbbox()
22
  if bbox:
23
+ result = result.crop(bbox)
 
 
24
 
25
+ # ็ตๆžœใ‚’ไธ€ๆ™‚ใƒ•ใ‚กใ‚คใƒซใซไฟๅญ˜
26
  result_path = "tmp.png"
27
+ result.save(result_path)
28
+
29
  return result_path
30
 
31
  def resize_image_aspect_ratio(image):