Skip to content

Instantly share code, notes, and snippets.

@sonkol
Last active January 21, 2025 11:18
Show Gist options
  • Save sonkol/82293c861aab1dfc501f2cd1b8f2f5ba to your computer and use it in GitHub Desktop.
Save sonkol/82293c861aab1dfc501f2cd1b8f2f5ba to your computer and use it in GitHub Desktop.
Average of pngs in folder
# Based on https://stackoverflow.com/a/17383621
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),float)
# Build up average pixel intensities, casting each image as an array of floats
for im in imlist:
imarr=numpy.array(Image.open(im).convert('RGB'),dtype=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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment