Tim*_*m R 11 python image-manipulation color-blending
我在python中拍摄了两张图像,并将第一张图像重叠到第二张图像上.我想做的是将图像混合在一起.有没有办法在python中执行此操作而不是for循环?
unu*_*tbu 16
PIL具有将两个RGB图像与固定alpha组合的blend功能:
out = image1 * (1.0 - alpha) + image2 * alpha
Run Code Online (Sandbox Code Playgroud)
但是,要使用blend,image1并image2必须是相同的大小.因此,要准备图像,您需要将每个图像粘贴到适当(组合)大小的新图像中.
由于alpha=0.5平均混合来自两个图像的RGB值的平均值,我们需要制作两个版本的全景图 - 一个使用img1一个顶部,一个使用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)
Run Code Online (Sandbox Code Playgroud)
IMG1:

IMG2:

结果:

如果你有两个RGBA图像,这是一种执行alpha合成的方法.
如果在将两个图像拼接在一起时想要柔和的边缘,可以将其与S型功能融合在一起。
这是一个简单的灰度示例:
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')
Run Code Online (Sandbox Code Playgroud)
如果将白色和黑色正方形混合,结果将类似于以下内容:
| 归档时间: |
|
| 查看次数: |
19968 次 |
| 最近记录: |