본문 바로가기

CS/AI | CV

Remove background image from image using PIL in Python

 

파이썬 PIL 라이브러리 사용해 이미지의 배경 제거

 

 

image1

 

image2

 

위 두 개의 이미지가 존재한다고 할 때,

오른쪽 이미지에서 고양이들만 제외한 채 왼쪽 이미지(배경)를 제거하고 새로운 png 파일로 출력하기

 

 

 

PIL Handbook에 따르면 ImageChops 함수로 구현 가능함

PIL Handbook

 

Handbook — Pillow (PIL Fork) 8.1.2 documentation

© Copyright 1995-2011 Fredrik Lundh, 2010-2021 Alex Clark and Contributors Revision 88bd672d.

pillow.readthedocs.io

ImageChops.subtract(image1, image2, scale, offset) => image
Subtracts two images, dividing the result by scale and adding the offset.
If omitted, scale defaults to 1.0, and offset to 0.0.
out = (image1 - image2) / scale + offset

 

 

 

결과 이미지를 고양이가 있는 이미지의 마스크로 이용할 수 있음

마스크가 0이 아닌 곳에 픽셀을 유지하고, 그렇지 않으면 원하는 배경색 만들어라

 

실습 코드

from PIL import Image
from PIL import ImageChops

image1 = Image.open("image1.jpg")  # no cats
image2 = Image.open("image2.jpg")  # with cats

image = ImageChops.subtract(image2, image1)

mask1 = Image.eval(image, lambda a: 0 if a <= 24 else 255)
mask2 = mask1.convert('1')

blank = Image.eval(image, lambda a: 0)

new = Image.composite(image2, blank, mask2)
new.show()

 

 

 

출력

 

 

 

설명

이미지는 JPG로 저장되기 때문에 손실 있음

그것들은 약간 다르게 렌더링 될 것이므로, 빼기 연산이 동일한 영역의 픽셀에 대해 항상 0 (즉, 검정색)이되는 것은 아님

그렇기 때문에 eval 함수의 의미있는 결과를 위해  lambda a: 0 if a <= 24 else 255 를 사용

 

손실이 없는 이미지를 사용하면 제대로 작동함

그렇다면 마스크를 만들 때 0 if a == 0 else 255 사용

 

 

 

주의

  1. 일부 '고양이' 픽셀이 실수로 배경 픽셀과 동일할 경우 검은 색 픽셀로 표시됨
  2. 사용할 이미지 두 개의 color model이 같아야 함(RGB인지 RGBA인지) 같지 않다면 image.convert('RGB') 이런 식으로 변환해 주기!

 

 

참고

stackoverflow

 

PIL remove background image from image

With a background image, would I be able to remove that background from another image and get all of the discrepancies? For example: Pretend I have these two images saved. How could I remove the f...

stackoverflow.com

 

 

 


Tiny Star