Photo2ShojoManga / utils /image_utils.py
tori29umai's picture
Update utils/image_utils.py
16a8ae4 verified
raw
history blame
1.86 kB
from PIL import Image
import numpy as np
import cv2
from rembg import remove
def background_removal(input_image_path):
"""
ๆŒ‡ๅฎšใ•ใ‚ŒใŸ็”ปๅƒใ‹ใ‚‰่ƒŒๆ™ฏใ‚’้™คๅŽปใ—ใ€้€ๆ˜Ž้ƒจๅˆ†ใ‚’็™ฝ่ƒŒๆ™ฏใซใƒ–ใƒฌใƒณใƒ‰ใ—ใฆ่ฟ”ใ™้–ขๆ•ฐใ€‚
้€้Žใ•ใ‚Œใฆใ„ใชใ„้ƒจๅˆ†ใงใƒˆใƒชใƒŸใƒณใ‚ฐใ‚‚่กŒใ„ใพใ™ใ€‚
"""
try:
input_image = Image.open(input_image_path).convert("RGBA")
except IOError:
print(f"Error: Cannot open {input_image_path}")
return None
# ่ƒŒๆ™ฏ้™คๅŽปๅ‡ฆ็†
result = remove(input_image)
# ้€้Žใ•ใ‚Œใฆใ„ใชใ„้ƒจๅˆ†ใ‚’ใƒˆใƒชใƒŸใƒณใ‚ฐ
bbox = result.getbbox()
if bbox:
result = result.crop(bbox)
# ็ตๆžœใ‚’ไธ€ๆ™‚ใƒ•ใ‚กใ‚คใƒซใซไฟๅญ˜
result_path = "tmp.png"
result.save(result_path)
return result_path
def resize_image_aspect_ratio(image):
# ๅ…ƒใฎ็”ปๅƒใ‚ตใ‚คใ‚บใ‚’ๅ–ๅพ—
original_width, original_height = image.size
# ใ‚ขใ‚นใƒšใ‚ฏใƒˆๆฏ”ใ‚’่จˆ็ฎ—
aspect_ratio = original_width / original_height
# ๆจ™ๆบ–ใฎใ‚ขใ‚นใƒšใ‚ฏใƒˆๆฏ”ใ‚ตใ‚คใ‚บใ‚’ๅฎš็พฉ
sizes = {
1: (1024, 1024), # ๆญฃๆ–นๅฝข
4/3: (1152, 896), # ๆจช้•ท็”ปๅƒ
3/2: (1216, 832),
16/9: (1344, 768),
21/9: (1568, 672),
3/1: (1728, 576),
1/4: (512, 2048), # ็ธฆ้•ท็”ปๅƒ
1/3: (576, 1728),
9/16: (768, 1344),
2/3: (832, 1216),
3/4: (896, 1152)
}
# ๆœ€ใ‚‚่ฟ‘ใ„ใ‚ขใ‚นใƒšใ‚ฏใƒˆๆฏ”ใ‚’่ฆ‹ใคใ‘ใ‚‹
closest_aspect_ratio = min(sizes.keys(), key=lambda x: abs(x - aspect_ratio))
target_width, target_height = sizes[closest_aspect_ratio]
# ใƒชใ‚ตใ‚คใ‚บๅ‡ฆ็†
resized_image = image.resize((target_width, target_height), Image.LANCZOS)
return resized_image
def base_generation(size, color):
canvas = Image.new("RGBA", size, color)
return canvas