如何使用PIL从100张图片中获得平均图片? [英] How to get an average picture from 100 pictures using PIL?

查看:233
本文介绍了如何使用PIL从100张图片中获得平均图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有100张分辨率相同的图片,我想将它们合并为一张图片。对于最终图片,每个像素的RGB值是该位置处的100张图片的平均值。我知道 getdata 函数可以在这种情况下工作,但是在PIL(Python图像库)中有更简单,更快捷的方法吗?

For example, I have 100 pictures whose resolution is the same, and I want to merge them into one picture. For the final picture, the RGB value of each pixel is the average of the 100 pictures' at that position. I know the getdata function can work in this situation, but is there a simpler and faster way to do this in PIL(Python Image Library)?

推荐答案

假设您的图像都是.png文件,它们都存储在当前工作目录中。下面的python代码将执行您想要的操作。正如Ignacio所说,使用numpy和PIL是关键。在构建平均像素强度时,您只需要在整数和浮点数组之间切换时要小心。

Let's assume that your images are all .png files and they are all stored in the current working directory. The python code below will do what you want. As Ignacio suggests, using numpy along with PIL is the key here. You just need to be a little bit careful about switching between integer and float arrays when building your average pixel intensities.

import os, numpy, PIL
from PIL import Image

# Access all PNG files in directory
allfiles=os.listdir(os.getcwd())
imlist=[filename for filename in allfiles if  filename[-4:] in [".png",".PNG"]]

# Assuming all images are the same size, get dimensions of first image
w,h=Image.open(imlist[0]).size
N=len(imlist)

# Create a numpy array of floats to store the average (assume RGB images)
arr=numpy.zeros((h,w,3),numpy.float)

# Build up average pixel intensities, casting each image as an array of floats
for im in imlist:
    imarr=numpy.array(Image.open(im),dtype=numpy.float)
    arr=arr+imarr/N

# Round values in array and cast as 8-bit integer
arr=numpy.array(numpy.round(arr),dtype=numpy.uint8)

# Generate, save and preview final image
out=Image.fromarray(arr,mode="RGB")
out.save("Average.png")
out.show()

下图是使用上述代码从一系列高清视频帧生成的。

The image below was generated from a sequence of HD video frames using the code above.

这篇关于如何使用PIL从100张图片中获得平均图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆