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): | |
""" | |
ๆๅฎใใใ็ปๅใใ่ๆฏใ้คๅปใใ้ๆ้จๅใ็ฝ่ๆฏใซใใฌใณใใใฆ่ฟใ้ขๆฐใ | |
ๅฐใใชใใใใ็ก่ฆใใฆใใชใใณใฐใ่กใใพใใ | |
Parameters: | |
- 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 | |
area_threshold=100 # ็ก่ฆใใๅฐใใ้ ๅใฎใใฏใปใซๆฐใฎ้พๅค | |
# ่ๆฏ้คๅปๅฆ็ | |
result = remove(input_image) | |
# ้้้จๅใฎใในใฏใไฝๆใใๅฐใใช้ ๅใ็ก่ฆ | |
alpha = result.split()[-1] # ใขใซใใกใใฃใณใใซใๅๅพ | |
bbox = alpha.getbbox() | |
if bbox: | |
# bbox ๅ ใฎ้้ใใใฆใใชใใใฏใปใซใๆฐใใ | |
cropped_alpha = alpha.crop(bbox) | |
non_transparent_pixels = sum(cropped_alpha.getdata()) // 255 | |
# ๆๅฎใใ้พๅคไปฅไธใฎ้ ๅใใใๅ ดๅใฎใฟใใชใใณใฐ | |
if non_transparent_pixels >= area_threshold: | |
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 |