본문 바로가기
카테고리 없음

누끼 파이썬 코드 rembg

by wanna_dev 2023. 12. 28.
from rembg import remove
from PIL import Image
import os

def process_roi(image_path, output_path):
    image = Image.open(image_path)
    width, height = image.size

    # Crop the ROI centered at the middle of the image
    roi_left = max(0, width // 2 - 175)
    roi_top = max(0, height // 2 - 175)
    roi_right = min(width, width // 2 + 175)
    roi_bottom = min(height, height // 2 + 175)

    roi = image.crop((roi_left, roi_top, roi_right, roi_bottom))

    # Save the ROI to a temporary file
    temp_roi_path = 'temp_roi.png'
    roi.save(temp_roi_path)

    with open(temp_roi_path, 'rb') as i:
        with open(output_path, 'wb') as o:
            input_data = i.read()
            output_data = remove(input_data)
            o.write(output_data)

    # Remove the temporary ROI file
    os.remove(temp_roi_path)

def resize_and_place_on_black_background(output_path, size=224):
    # Load the output image with the background removed
    image = Image.open(output_path)
    image = image.convert("RGBA")

    # Resize the image to 224x224
    image = image.resize((size, size), Image.ANTIALIAS)

    # Create a black background image of size 224x224
    background = Image.new("RGBA", (size, size), (0, 0, 0, 255))

    # Paste the image onto the black background using alpha_composite
    result = Image.alpha_composite(background, image)

    # Save the final image
    result.save(output_path)

if __name__ == "__main__":
    input_path = './2.jpg'
    output_path = 'output.png'

    process_roi(input_path, output_path)
    resize_and_place_on_black_background(output_path, size=224)

    print('done')

 

 

개발을 하다보면, 누끼를 따야할 때가 많은데

rembg 라이브러리를 사용해서 누끼를 따주는 코드를 만들었습니다.