tori29umai commited on
Commit
2dd8a35
โ€ข
1 Parent(s): 16a8ae4

Update utils/image_utils.py

Browse files
Files changed (1) hide show
  1. utils/image_utils.py +17 -5
utils/image_utils.py CHANGED
@@ -6,21 +6,33 @@ from rembg import remove
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"
 
6
  def background_removal(input_image_path):
7
  """
8
  ๆŒ‡ๅฎšใ•ใ‚ŒใŸ็”ปๅƒใ‹ใ‚‰่ƒŒๆ™ฏใ‚’้™คๅŽปใ—ใ€้€ๆ˜Ž้ƒจๅˆ†ใ‚’็™ฝ่ƒŒๆ™ฏใซใƒ–ใƒฌใƒณใƒ‰ใ—ใฆ่ฟ”ใ™้–ขๆ•ฐใ€‚
9
+ ๅฐใ•ใชใƒ‰ใƒƒใƒˆใ‚’็„ก่ฆ–ใ—ใฆใƒˆใƒชใƒŸใƒณใ‚ฐใ‚‚่กŒใ„ใพใ™ใ€‚
10
+
11
+ Parameters:
12
+ - input_image_path: ่ƒŒๆ™ฏ้™คๅŽปใ™ใ‚‹็”ปๅƒใฎใƒ‘ใ‚น
13
  """
14
  try:
15
  input_image = Image.open(input_image_path).convert("RGBA")
16
  except IOError:
17
  print(f"Error: Cannot open {input_image_path}")
18
  return None
19
+
20
+ area_threshold=100 # ็„ก่ฆ–ใ™ใ‚‹ๅฐใ•ใ„้ ˜ๅŸŸใฎใƒ”ใ‚ฏใ‚ปใƒซๆ•ฐใฎ้–พๅ€ค
21
+
22
  # ่ƒŒๆ™ฏ้™คๅŽปๅ‡ฆ็†
23
  result = remove(input_image)
24
 
25
+ # ้€้Ž้ƒจๅˆ†ใฎใƒžใ‚นใ‚ฏใ‚’ไฝœๆˆใ—ใ€ๅฐใ•ใช้ ˜ๅŸŸใ‚’็„ก่ฆ–
26
+ alpha = result.split()[-1] # ใ‚ขใƒซใƒ•ใ‚กใƒใƒฃใƒณใƒใƒซใ‚’ๅ–ๅพ—
27
+ bbox = alpha.getbbox()
28
  if bbox:
29
+ # bbox ๅ†…ใฎ้€้Žใ•ใ‚Œใฆใ„ใชใ„ใƒ”ใ‚ฏใ‚ปใƒซใ‚’ๆ•ฐใˆใ‚‹
30
+ cropped_alpha = alpha.crop(bbox)
31
+ non_transparent_pixels = sum(cropped_alpha.getdata()) // 255
32
+
33
+ # ๆŒ‡ๅฎšใ—ใŸ้–พๅ€คไปฅไธŠใฎ้ ˜ๅŸŸใŒใ‚ใ‚‹ๅ ดๅˆใฎใฟใƒˆใƒชใƒŸใƒณใ‚ฐ
34
+ if non_transparent_pixels >= area_threshold:
35
+ result = result.crop(bbox)
36
 
37
  # ็ตๆžœใ‚’ไธ€ๆ™‚ใƒ•ใ‚กใ‚คใƒซใซไฟๅญ˜
38
  result_path = "tmp.png"