Spaces:
Running
on
Zero
Running
on
Zero
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 |