多张图片拼接一个图像效果的实现
年终了,划个水就很开心,搞个小玩意出来开心一下
效果示例
实现代码
也没什吗核心技术难度,开心就好.这里直接列出来三个核心函数
def read_base_pictures(source_path, file_type):
"""
读取文件夹中的图片作为背景图
:param source_path: 背景图文件夹
:param file_type: 背景图扩展名(.jpg)
:return: None
"""
path_files = os.listdir(source_path)
for item_name in path_files:
if item_name.endswith(file_type): # 扩展名是图片
# 调用cv2.imread读入图片,读入格式为IMREAD_COLOR
full_name = source_path + "/" + item_name
img_mat = cv2.imread(full_name, cv2.IMREAD_COLOR)
background_arr.append(img_mat)
def make_background(output_size, picture_num):
# 验证输出尺寸合理性和拼接行列数量
if output_size not in output_define:
print('the output size should be 256. 512. 1024 or 2048')
return
if output_size % picture_num != 0:
print('output_size should be divisible by picture_num!')
return
# 背景图像的尺寸
size = int(output_size / picture_num)
print(output_size, picture_num, size)
# 构建一张空白图(3通道)
back_img = np.zeros((output_size, output_size, 3), dtype=np.uint8)
max_index = len(background_arr) - 1 # 从零开始逐-1
for row in range(picture_num):
for col in range(picture_num):
index = random.randint(0, max_index)
item_mat = cv2.resize(background_arr[index], (size, size))
s1 = row * size
e1 = (row + 1) * size
s2 = col * size
e2 = (col + 1) * size
back_img[s1:e1, s2:e2] = item_mat
return back_img
def make_foreground(foreground_mat, background_mat):
f_w, f_h, f_d = foreground_mat.shape
if f_w != f_h or f_d != 3:
print('本程序当前只支持等宽高的3通道彩色图片处理!')
return
b_w, b_h, b_d = background_mat.shape
fore_resize = cv2.resize(foreground_mat, (b_w, b_h))
dst = cv2.addWeighted(fore_resize, 0.4, background_mat, 0.6, 0)
cv2.imwrite('./result/result.jpg', dst)