使用Python混合多个图像

2024-10-03 17:19:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试组合多个相同高度和宽度的图像,以查看整体模式。每个图像应该具有相同的“权重”或“透明度”,但我不知道如何做到这一点。在研究了{a1}和{a2}之后,普遍的共识似乎是这样做:

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

我正试图用下面的代码来实现这一点,但它似乎不起作用,因为无论我做什么,我都会得到一个混合了列表中第一个和最后一个图像的图像。所以要么我误解了怎么做,要么我做错了什么。如何混合jpeg_列表中的所有图像?我不知道这是否与此有关,但我的输入图像是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))

Tags: path代码in图像imageimgcv2list
1条回答
网友
1楼 · 发布于 2024-10-03 17:19:56

您正在将加权图像添加到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))

相关问题 更多 >