[英]Linear light blending in Python with 50% opacity
我正在尝试在 Python 中使用线性照明进行混合。 但是,我想以 50% 的不透明度与背景图像混合,就像您如何在 Photoshop 中更改不透明度一样。
这是我的代码:
import cv2
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
# # Decrease opacity of background
img = Image.open('industrial_storage.png')
# img.putalpha(127) # Half alpha; alpha argument must be an int
# img.save('industrial_storage.png')
# read image and convert to float in range 0 to 1
detail = cv2.imread('Detail.png', cv2.IMREAD_UNCHANGED).astype("float32") / 255.0
detail = cv2.cvtColor(detail, cv2.COLOR_BGR2BGRA)
background = cv2.imread('industrial_storage.png', cv2.IMREAD_UNCHANGED).astype("float32") / 255.0
# apply linear light backgrounding
linear_light = (background > 0.5) * (detail + 2*(background-0.5)) + (background <= 0.5) * (detail + 2*background - 1)
result = (255 * linear_light).clip(0, 255).astype(np.uint8)
# save results
cv2.imwrite('result.png', result)
在这段代码中,我使用了https://www.deepskycolors.com/archivo/2010/04/21/formulas-for-Photoshop-blending-modes.html上给出的线性光混合公式。 我还为这两个图像创建了 alpha 通道。 背景图像的所有像素都具有 127 的 alpha 通道(半不透明度)。 但是,Alpha 混合不起作用。 代码给了我结果:
cv2.addWeighted
方法用于混合图像。 由于您想要 50% 的不透明度,因此可以通过以下方式完成:
import cv2
img_a = cv2.imread("industrial_storage.png")
img_b = cv2.imread("Detail.png")
alpha = 0.5
# Since img_a and img_b are of different resolution
# We resize img_a to the size of img_b
img_a_resized = cv2.resize(img_a, (img_b.shape[1], img_b.shape[0]))
# Blending the images
img_final = cv2.addWeighted(img_a_resized, alpha, img_b, 1 - alpha, 0.0)
cv2.imwrite("final_image.png", img_final)
最终图像是:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.