Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
87 views
in Technique[技术] by (71.8m points)

python - How to add images on top of each other in for loop?

I've got 4 images. I want to get 1 image which is an overlay of all 4 images. My code doesn't do this correctly. Here is my code so far:

framefiles = [file for file in os.listdir(inputvideopath) if os.path.isfile(os.path.join(inputvideopath, file)) and file.endswith('jpg')]
for frame_id, frame in enumerate(framefiles):
    if frame_id < 1:
        img1 = cv2.imread(output_dir + frame)
    if frame_id >= 1:
        img2 = cv2.imread(output_dir + frame)
        final_img = cv2.add(img1,img2)
        cv2.imshow('hh',final_img)
        cv2.waitKey(0)

Any help would be greatly appreciated. Thank you.

question from:https://stackoverflow.com/questions/65936683/how-to-add-images-on-top-of-each-other-in-for-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You better DON'T use loops, if you don't want to handle exact weights. With each iteration you'd give the newly overlayed image proportionately too much weight w.r.t. to the already merged image.

Let's see these four images:

1

2

3

4

I prepared some code to visualize:

import cv2
import numpy as np

images = ['1.png', '2.png', '3.jpg', '4.jpg']
images = [cv2.resize(cv2.imread(i), (400, 400)) for i in images]

# Don't do loops, m'kay?
output = images[0]
for i, image in enumerate(images[1:]):
    output = cv2.addWeighted(output, 0.5, image, 0.5, 0)
    cv2.imwrite(str(i) + '.png', output)

# Do linear blending using all images at once.
output = (np.array(images) / len(images)).sum(axis=0).astype(np.uint8)
cv2.imwrite('output.png', output)

The (intermediate) output(s) of the loop look like that:

i1

i2

i3

The night image is most prominent, whereas Paddington can be hardly seen.

It'd be better to divide all images by the number of images you want to overlay, and then sum them. Using NumPy, that's the given one-liner, and that'd be the output:

output

----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.16299-SP0
Python:        3.8.5
NumPy:         1.19.5
OpenCV:        4.5.1
----------------------------------------

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...