ProgramingTip

Python에서 PIL을 사용하여 이미지를 다른 이미지에 어떻게 합성하고 있습니까?

bestdevel 2020. 11. 27. 21:05
반응형

Python에서 PIL을 사용하여 이미지를 다른 이미지에 어떻게 합성하고 있습니까?


다운로드 가능한 바탕 화면 배경 무늬로 변환 클릭하여 새로 생성 된 흰색 배경에 배치해야합니다. 따라서 프로세스는 다음과 같이 진행됩니다.

  1. 1440x900 크기의 새 흰색 이미지 생성
  2. 기존 이미지를 상단 중앙에 배치
  3. 단일 이미지로 저장

PIL에서 사용할 수있는 ImageDraw개체를 수 있습니다. 누구든지 추천 할 수있는 제안이나 링크?


이 이미지 인스턴스의 paste메서드 로 수행 할 수 있습니다 .

from PIL import Image
img = Image.open('/path/to/file', 'r')
img_w, img_h = img.size
background = Image.new('RGBA', (1440, 900), (255, 255, 255, 255))
bg_w, bg_h = background.size
offset = ((bg_w - img_w) // 2, (bg_h - img_h) // 2)
background.paste(img, offset)
background.save('out.png')

이것과 다른 많은 PIL 트릭은 Nadia Alramli의 PIL Tutorial 에서 선택할 수 있습니다.


unutbus 답변을 기반으로 :

#!/usr/bin/env python

from PIL import Image
import math


def resize_canvas(old_image_path="314.jpg", new_image_path="save.jpg",
                  canvas_width=500, canvas_height=500):
    """
    Place one image on another image.

    Resize the canvas of old_image_path and store the new image in
    new_image_path. Center the image on the new canvas.
    """
    im = Image.open(old_image_path)
    old_width, old_height = im.size

    # Center the image
    x1 = int(math.floor((canvas_width - old_width) / 2))
    y1 = int(math.floor((canvas_height - old_height) / 2))

    mode = im.mode
    if len(mode) == 1:  # L, 1
        new_background = (255)
    if len(mode) == 3:  # RGB
        new_background = (255, 255, 255)
    if len(mode) == 4:  # RGBA, CMYK
        new_background = (255, 255, 255, 255)

    newImage = Image.new(mode, (canvas_width, canvas_height), new_background)
    newImage.paste(im, (x1, y1, x1 + old_width, y1 + old_height))
    newImage.save(new_image_path)

resize_canvas()

Pillow는 Python 2.X 및 Python 3.X에서 작동하므로 python-imaging 대신 Pillow ( Documentation , GitHub , PyPI )를 사용해야합니다.


이것은 비슷한 일을하는 것입니다.

내가 시작한 곳은 포토샵에서 '흰색 배경'을 생성하고 PNG 파일로 내보내는 것이 었습니다. 그것이 내가 im1 (이미지 1)을 얻은 곳입니다. 그런 다음 붙여 넣기 기능을 사용하면 훨씬 쉽습니다.

from PIL import Image

im1 = Image.open('image/path/1.png')
im2 = Image.open('image/path/2.png')
area = (40, 1345, 551, 1625)  
im1.paste(im2, area)
                   l>(511+40) l>(280+1345)
         |    l> From 0 (move, 1345px down) 
          -> From 0 (top left, move 40 pixels right)

Okay so where did these #'s come from? (40, 1345, 551, 1625) im2.size (511, 280) Because I added 40 right and 1345 down (40, 1345, 511, 280) I must add them to the original image size which = (40, 1345, 551, 1625)

im1.show() 

새로운 이미지를 보여주기 위해


Image.blend()? [ 링크 ]

또는 더 나은 방법 Image.paste()은 동일한 링크입니다.


너무 늦었을 수도 있지만 이러한 이미지 작업을 위해 원본 이미지가있는 모델에서 ImageSpecField [ link ]를 사용 합니다.

참고 URL : https://stackoverflow.com/questions/2563822/how-do-you-composite-an-image-onto-another-image-with-pil-in-python

반응형