使用Python混合多个图像



我正在尝试组合多个相同高度和宽度的图像,以查看整体模式。每个图像应该具有相同的";重量;或";透明性";,但我不知道该怎么做。在看了这里和这里之后,普遍的共识似乎是这样做:

blendedImage = weight_1 * image_1 + weight_2 * image_2 + ... + weight_n * image_n

我正试图用下面的代码做到这一点,但它似乎不起作用,因为无论我做什么,我都会得到一个混合了列表中第一个和最后一个图像的图像。所以,要么我误解了该怎么做,要么我做错了什么。如何混合jpeg_list中的所有图像?我不知道这是否与此有关,但我的输入图像是3通道JPG或3通道PNG。

到目前为止我的代码:

import os
import cv2

def prepend(list, str): 

# Using format() 
str += '{0}'
list = [str.format(i) for i in list] 
return(list) 

path = "EvalImages/"
jpeg_list = os.listdir(path)
if '.DS_Store' in jpeg_list: jpeg_list.remove('.DS_Store')
jpeg_list = prepend(jpeg_list, path)
uniWeight = (1/len(jpeg_list))
print(uniWeight)
print(jpeg_list)
aggregate_file = cv2.imread(jpeg_list[0]) * uniWeight
del jpeg_list[0]
for i in range(len(jpeg_list)):
print(i)
next_img = cv2.imread(jpeg_list[i])
dst = aggregate_file + (next_img*uniWeight)
cv2.imshow('dst', dst)
cv2.imwrite('TestContainer/evalimage3.png', dst)
height, width, channels = next_img.shape
print(jpeg_list[i] + " | Size: " + str(width) + "x" + str(height) + " | Channels:" +  str(channels))

您将加权图像添加到dst,但您打算将它们添加到aggregate_file

你的imshow也没有效果,因为没有任何waitKey。实际显示窗口及其内容并使其对输入做出反应非常重要。

我会这么做:

import pathlib
import numpy as np
import cv2 as cv
path = pathlib.Path("EvalImages")
jpeg_list = [elem for elem in path.iterdir() if elem.name != '.DS_Store']
# initialized to size of first image
accumulator = None
for i, filepath in enumerate(jpeg_list):
print(i, filepath)
img = cv.imread(str(filepath))
if accumulator is None:
accumulator = np.zeros_like(img, dtype=np.uint32)
accumulator += img
# divide once to avoid adding up errors from many divisions
# values are now back in an 8 bit range
accumulator /= len(jpeg_list)
# convert back to uint8 so imwrite() knows to save it as 8 bit, not 32 bit
cv.imwrite('TestContainer/evalimage3.png', accumulator.astype(np.uint8))

最新更新