web-dev-qa-db-ja.com

python

pythonで2つの画像を取得し、最初の画像を2番目の画像に重ねています。私がやりたいのは、それらが重なる場所で画像をブレンドすることです。 forループ以外にpythonでこれを行う方法はありますか?

12
Tim R

PILには blend function があり、2つのRGB画像を固定アルファで結合します。

out = image1 * (1.0 - alpha) + image2 * alpha

ただし、blendを使用するには、image1image2が同じサイズである必要があります。したがって、画像を準備するには、それぞれを適切な(結合された)サイズの新しい画像に貼り付ける必要があります。

alpha=0.5とブレンドすると、両方の画像のRGB値が均等に平均化されるため、2つのバージョンのパノラマを作成する必要があります。1つはimg1、もう1つはimg2です。次に、オーバーラップのない領域は、一致するRGB値を持ち(したがって、それらの平均は変更されません)、オーバーラップの領域は必要に応じてブレンドされます。


import operator
from PIL import Image
from PIL import ImageDraw

# suppose img1 and img2 are your two images
img1 = Image.new('RGB', size=(100, 100), color=(255, 0, 0))
img2 = Image.new('RGB', size=(120, 130), color=(0, 255, 0))

# suppose img2 is to be shifted by `shift` amount 
shift = (50, 60)

# compute the size of the panorama
nw, nh = map(max, map(operator.add, img2.size, shift), img1.size)

# paste img1 on top of img2
newimg1 = Image.new('RGBA', size=(nw, nh), color=(0, 0, 0, 0))
newimg1.paste(img2, shift)
newimg1.paste(img1, (0, 0))

# paste img2 on top of img1
newimg2 = Image.new('RGBA', size=(nw, nh), color=(0, 0, 0, 0))
newimg2.paste(img1, (0, 0))
newimg2.paste(img2, shift)

# blend with alpha=0.5
result = Image.blend(newimg1, newimg2, alpha=0.5)

img1:

enter image description here

img2:

enter image description here

結果:

enter image description here


2つのRGBA画像がある場合 ここに方法があります を実行するには アルファ合成

16
unutbu

2つの画像をつなぎ合わせるときにソフトエッジが必要な場合は、シグモイド関数を使用してそれらをブレンドできます。

簡単なグレースケールの例を次に示します。

import numpy as np
import matplotlib.image
import math

def sigmoid(x):
  y = np.zeros(len(x))
  for i in range(len(x)):
    y[i] = 1 / (1 + math.exp(-x[i]))
  return y

sigmoid_ = sigmoid(np.arange(-1, 1, 1/50))
alpha = np.repeat(sigmoid_.reshape((len(sigmoid_), 1)), repeats=100, axis=1)

image1_connect = np.ones((100, 100))
image2_connect = np.zeros((100, 100))
out = image1_connect * (1.0 - alpha) + image2_connect * alpha
matplotlib.image.imsave('blend.png', out, cmap = 'gray')

白と黒の正方形をブレンドすると、結果は次のようになります。

enter image description here+enter image description here=enter image description here

9
Massyanya