将透明背景png转换为灰度图:
import cv2
import numpy as np
def convert_png_to_black_and_white(input_path, output_path):
# 读取PNG图像
image = cv2.imread(input_path, cv2.IMREAD_UNCHANGED)
# 提取图像的Alpha通道
alpha_channel = image[:, :, 3]
# 将Alpha通道转换为二值图像(黑白图像)
_, binary_image = cv2.threshold(alpha_channel, 0, 255, cv2.THRESH_BINARY)
# 创建一个与原始图像大小相同的白色图像
white_image = 255 * np.ones_like(image[:, :, :3])
# 将Alpha通道为0的像素设为黑色
white_image[binary_image == 0] = [0, 0, 0]
# 保存黑白图像
cv2.imwrite(output_path, white_image)
input_path = 'snail.png' # 输入PNG图像的路径
output_path = 'snail_output.png' # 输出黑白图像的路径
convert_png_to_black_and_white(input_path, output_path)
缩小灰度图尺度:
import cv2
import numpy as np
def resize_and_copy_image(input_path, output_path):
# 读取PNG图像
image = cv2.imread(input_path, cv2.IMREAD_UNCHANGED)
# 缩小图像尺寸
scale = 0.8
resized_image = cv2.resize(image, None, fx=scale, fy=scale)
# 创建与原始图像大小相同的黑色背景
background = np.zeros_like(image)
# 计算在背景上粘贴图像的起始位置
start_x = int((background.shape[1] - resized_image.shape[1]) / 2)
start_y = int((background.shape[0] - resized_image.shape[0]) / 2)
# 将缩小后的图像复制到背景上
background[start_y:start_y+resized_image.shape[0], start_x:start_x+resized_image.shape[1]] = resized_image
# 保存结果图像
cv2.imwrite(output_path, background)
# 示例用法
input_path = 'snail_output.png' # 输入PNG图像的路径
output_path = 'snail_output_scale.png' # 输出结果图像的路径
resize_and_copy_image(input_path, output_path)
应用到新背景:
import cv2
mask = cv2.imread('snail_output_scale.png')
mask = cv2.resize(mask, (300,300), interpolation = cv2.INTER_AREA)
mask = cv2.GaussianBlur(mask, (35, 35), 0)
mask = mask / 255 # 除以 255,計算每個像素的黑白色彩在 255 中所佔的比例
img = cv2.imread('snail.png') # 開啟圖片
img = cv2.resize(img, (300,300), interpolation = cv2.INTER_AREA)
img = img / 255 # 除以 255,計算每個像素的色彩在 255 中所佔的比例
bg = cv2.imread('bkg.jpg') # 開啟圖片
bg = cv2.resize(bg, (300,300), interpolation = cv2.INTER_AREA)
bg = bg / 255 # 除以 255,計算每個像素的色彩在 255 中所佔的比例
out = bg * (1 - mask) + img * mask # 根據比例混合
out = (out * 255).astype('uint8') # 乘以 255 之後轉換成整數
cv2.imwrite('snail_blurred.png',out)
参考:[1]