Finding the difference image between multiple images
<p>I've taken multiple screenshots from a webcam on my campus and I have taken the average of the 300 screenshots and it gives me an image with many ghostly people. I am trying to figure out how to get the difference image between the images so that I can change the differences to red to show is more clearly. I just need some help getting an idea of where to start. I know I need to subtract the first image by the second, and then that image by the third, but I'm not sure of a way to do that in Python.</p>

<pre><code>import os, os.path, time
import matplotlib.pyplot as mplot
from PIL import Image
import numpy as np

files=os.listdir('./images')
print files

image=[]

for file in files:
    img=Image.open('./images/'+file)
    img=np.float32(img)
    image.append(img)

avg_img=[]

for img in image:
    try:
        avg_img+=img
    except:
        avg_img=img

avg_img/=len(image)
avg_img=np.clip(avg_img, 0, 255)
avg_img=np.uint8(avg_img)
mplot.imshow(avg_img)
mplot.show()
</code></pre>

<p>There are tons of ways to do this, but I will first keep closest to what you currently have. Then I will show a more compact way.</p>

<pre><code>import os, os.path, time
import matplotlib.pyplot as mplot
from PIL import Image
import numpy as np

files=os.listdir('./images')
print files

image=[]

for file in files:
    img=Image.open('./images/'+file)
    img=np.float32(img)
    image.append(img)

avg_img=np.zeros_like(image[0])

for img in image:
    avg_img += img

avg_img/=len(image)
avg_img=np.clip(avg_img, 0, 255)
avg_img=np.uint8(avg_img)
mplot.imshow(avg_img)
mplot.show()

# get series of differences
differences = []
for img0, img1 in zip(image[:-1], image[1:]):
    differences.append(img1 - img0)
</code></pre>

<p>Here is an easier way using numpy.</p>

<pre><code>import os, os.path, time
import matplotlib.pyplot as mplot
from PIL import Image
import numpy as np

files = os.listdir('./images')
print files

img = Image.open(os.path.join('./images', files[0])

image_stack = np.ndarray((len(files), img.shape[0], img.shape[1], 3), dtype=np.float32)

for i, file in enumerate(files):
    img = Image.open('./images/'+file)
    img = np.float32(img)
    image_stack[i] = img

avg_img = np.mean(image_stack, axis=0)
avg_img = np.clip(avg_img, 0, 255)
avg_img = avg_img.astype(np.uint8)

mplot.imshow(avg_img)
mplot.show()

difference_stack = image_stack[1:] - image_stack[:-1]
</code></pre>

<p>I doubt your webcam image stores floats, but maybe that is the case.</p>

python image numpy difference