본문 바로가기
Python

python 이미지 데이터 합성 : 알파블렌딩 (겹쳐보이기)

by pnnote 2023. 5. 16.
반응형

이미지를 합성할때 배경이미지에 전경이미지를 완전히 합성하는게 아니라 투명하도록 배경이미지와 전경이미지가 둘다 사라지지않고 보여야하는 경우가 있습니다. 그럴경우 다음과 같이 코드를 수행합니다.

from PIL import Image

background = Image.open("./background/bg.png")
overlay = Image.open("./foreground/fg.png")

overlay = overlay.resize((1280, 720))

background = background.convert("RGBA")
overlay = overlay.convert("RGBA")

new_img = Image.blend(background, overlay, 0.2)
new_img.save("new.png","PNG")

background image + foreground image

 

result

 

위와 같은 방식을 사용할때 문제는 배경이미지와 전경이미지의 사이즈가 같아야합니다. 

따라서 배경이미지의 특정한 부분에 전경이미지를 겹쳐보이고 싶다면 붙이고 싶은 위치의 배경이미지를 crop해서 전경이미지와 합성하고 그걸 다시 배경이미지에 붙이는 방법을 사용하면 됩니다.

 

crop_img = background_img[y-int(fg_h / 2):y-int(fg_h / 2) +fg_h, x - int(fg_w / 2): x - int(fg_w / 2) +fg_w]

background = Image.fromarray(crop_img)
overlay = Image.fromarray(foreground_objects[i])
background = background.convert("RGBA")
overlay = overlay.convert("RGBA")

new_img = Image.blend(background, overlay, 0.3)

background_img[y - int(fg_h / 2) + locs[0], x - int(fg_w / 2) + locs[1]] = numpy_image[locs[0], locs[1]]

 

 

반응형

'Python' 카테고리의 다른 글

Python logging 모듈 사용법  (0) 2023.05.27
python 한글 파일명 이미지 저장하기  (0) 2023.05.19
프린터 인쇄 명령어 python  (0) 2023.05.10
API 요청 방법  (0) 2023.05.09
Pytorch Quantization  (0) 2023.04.25