반응형
모델 준비
import os
# clone the repository
%cd /content
if not os.path.exists('MODNet'):
!git clone https://github.com/ZHKKKe/MODNet
%cd MODNet/
# dowload the pre-trained ckpt for image matting
pretrained_ckpt = 'pretrained/modnet_photographic_portrait_matting.ckpt'
if not os.path.exists(pretrained_ckpt):
!gdown --id 1mcr7ALciuAsHCpLnrtG_eop5-EYhbCmz \
-O pretrained/modnet_photographic_portrait_matting.ckpt
이미지 업로드
import shutil
import os
from google.colab import files
# clean and rebuild the image folders
input_folder = 'demo/image_matting/colab/input'
if os.path.exists(input_folder):
shutil.rmtree(input_folder)
os.makedirs(input_folder)
output_folder = 'demo/image_matting/colab/output'
if os.path.exists(output_folder):
shutil.rmtree(output_folder)
os.makedirs(output_folder)
# upload images (PNG or JPG)
image_names = list(files.upload().keys())
for image_name in image_names:
shutil.move(image_name, os.path.join(input_folder, image_name))
추론(Inference)
!python -m demo.image_matting.colab.inference \
--input-path demo/image_matting/colab/input \
--output-path demo/image_matting/colab/output \
--ckpt-path ./pretrained/modnet_photographic_portrait_matting.ckpt
Visualization
import numpy as np
from PIL import Image
def combined_display(image, matte):
# calculate display resolution
w, h = image.width, image.height
rw, rh = 800, int(h * 800 / (3 * w))
# obtain predicted foreground
image = np.asarray(image)
if len(image.shape) == 2:
image = image[:, :, None]
if image.shape[2] == 1:
image = np.repeat(image, 3, axis=2)
elif image.shape[2] == 4:
image = image[:, :, 0:3]
matte = np.repeat(np.asarray(matte)[:, :, None], 3, axis=2) / 255
foreground = image * matte + np.full(image.shape, 255) * (1 - matte)
# combine image, foreground, and alpha into one line
combined = np.concatenate((image, foreground, matte * 255), axis=1)
combined = Image.fromarray(np.uint8(combined)).resize((rw, rh))
return combined
# visualize all images
image_names = os.listdir(input_folder)
for image_name in image_names:
matte_name = image_name.split('.')[0] + '.png'
image = Image.open(os.path.join(input_folder, image_name))
matte = Image.open(os.path.join(output_folder, matte_name))
display(combined_display(image, matte))
print(image_name, '\n')
결과 저장
zip_filename = 'matte.zip'
if os.path.exists(zip_filename):
os.remove(zip_filename)
os.system(f"zip -r -j {zip_filename} {output_folder}/*")
files.download(zip_filename)
<< 원본 파일 >>
https://livecodestream.dev/post/remove-the-background-from-images-using-ai-and-python/
Remove the background from images using AI and Python
Learn how to remove the background using AI, like that super trending app, but powered by Python.
livecodestream.dev
반응형
'프로그램 개발해서 돈벌기 > AI' 카테고리의 다른 글
[무료] AI로 그림 그리기 프로그램 소개 (모델 내장) (0) | 2023.02.28 |
---|---|
파이션 Stable Diffusion 초 간단 예제 (0) | 2023.02.24 |
시맨틱 세그먼테이션(Semantic Segmentation) (0) | 2023.02.24 |
[ML 왕초보 개념] 머신러닝 정의와 학습 종류 (0) | 2023.02.23 |
GAN 구조 개요 (0) | 2023.02.23 |
댓글