Digitally Averaging Time Magazines Covers From 2021

In this project I will take the average of every Time magazines cover from last year using Python. By taking the average I mean taking the average RGB-values for all the pixels.

This code can be applied to any collection of images. Just be sure to set the correct variables in the following steps to determine, where the images are, what dimensions do you want them to have, and what filetypes they are.

Resizing images to same dimensions

I assume you have all the images in a subfolder called โ€œtimeโ€.

First let us import the packages needed for this example.

import cv2, os, PIL
from PIL import Image
import numpy as np

Then let us set variables needed later. The img_dims -variable is a tubble containing the dimensions you want your images to be resized to.

img_folder = "/time"
img_dims = (2363,3150)

Next let us access all the images and save them to a list. If your files are not .jpeg or .jpg, change the list items.

cwd = os.getcwd()
allfiles=os.listdir(cwd + img_folder)
imlist=[filename for filename in allfiles if  filename[-4:] in [".jpg",".jpeg"]]

Next, I will define a function for stretching the images to the correct dimensions (img_dims).

def scretch(image, dim=(2363,3150)):
    img = cv2.imread(image, 1)
    img_scretched = cv2.resize(img, dim)
    return img_scretched

And then we can use this function to resize the images to the correct size.

N=len(imlist)
for im in range(N):
    image = "." + img_folder + "/" + imlist[im]
    w,h=Image.open(image).size
    if (w,h) != img_dims:
        img_scretched = scretch(image, img_dims)
        cv2.imwrite(image, img_scretched)

Now we have all the images in the correct size.

Taking the average RGB-values

First, we can take the width and height of the (resized) images.

w,h= img_dims

Then we can create a numpy array of floats to store the average values.

arr = np.zeros((h,w,3), np.float64)

Next, let us cast each image as array of floats and divide by number of images to take the average.

for im in imlist:
  image = "." + img_folder + "/" + im
  imarr = np.array(Image.open(image), dtype = np.float64)
  arr = arr + imarr/N

Finally, we can round the values and cast as integer. Then we can generate and save the final image.

final_img = Image.fromarray(arr,mode="RGB")
final_img.save("FinalImage.png")

This is what my final image looks like:

Average of Time Magazine 2021 Covers