Home > Mobile >  averaging each two image in 10000 images array in python
averaging each two image in 10000 images array in python

Time:10-27

I am new in python. I wonder if you can give me an idea on how I can average each successive two images array in matrix of 10000 images. I want to down sample the cadence of my film. I found the following code, but I want to average a matrix of image and not png ou jpeg format.

    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[".tif",".TIF"]]

# 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 16-bit integer
arr = numpy.array(numpy.round(arr),dtype=numpy.uint16)

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

Thank you in advance,

CodePudding user response:

Python

You will need a way to get [[img0, img1], [img2, img3], [img4, img5], ...].

So you will need to generate numbers as:

0, 1
2, 3
4, 5
...
998, 999

To generate these pairs:

pairs = [[2 * i, 2 * i   1] for i in range(500)]

Now you can loop through pairs and select the images as:

for pair in pairs:
    average(imgs[pair[0]], imgs[pair[1]])

PS: Please notice this will be really slow. A better way would be using numpy's reshape and mean().

Numpy

Let's say you have access to numpy and you have a list of 1000 images as imgs. I'm generating 1000 25x25 arrays to be images:

import numpy as np

imgs = np.array([np.ones((25, 25)) * i for i in range(1000)])
image_pairs = imgs.reshape((500, 2, 25, 25))
print(np.mean(image_pairs, axis=1))
  • Related