Search code examples
pythonimagesubtraction

Python Code to image subtract consecutive images


I have a bunch of images named 0.jpg, 1.jpg, 2.jpg, etc. I am trying to create a code to subtract consecutive images. I have the subtraction code down, but I can't seem to figure out how to loop through the folder that has all these images to do consecutive image subtractions such that: 0.jpg - 1.jpg, 1.jpg - 2.jpg, 2.jpg - 3.jpg, etc.

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

directory ='/home/pi/Desktop/tryy'

filelist = os.listdir(directory)
filelists = sorted(filelist,key=lambda x:int(os.path.splitext(x)[0]))

for i in filelists:
    i = 0
    imgX = cv2.imread(filelists[i])
    imgY = cv2.imread(filelists[i+1])
    imgZ = cv2.absdiff(imgX, imgY)
    
    thresh = cv2.threshold(imgZ,30, 255, cv2.THRESH_BINARY)[1]
    np.set_printoptions(threshold=np.inf)
    data = asarray(thresh)
    print(data)

#Movement Output
    Maximum = np.max(data)
    print(Maximum)

    if Maximum == 255:
        print("Movement")
    else:
        print("No Movement")
    i= i+1

Solution

  • You could use the built-in zip function like this:

    for x, y in zip(filelists[:-1], filelists[1:]):
        imgX = cv2.imread(os.path.join(directory, x)).astype(np.float_)
        imgY = cv2.imread(os.path.join(directory, y)).astype(np.float_)
        imgZ = cv2.absdiff(imgX, imgY)
    

    Note that if directory is not located in the current directory, you must pass the full path of the images to cv2.imread. Besides, you should convert the images to float_ in order to avoid integer overflow/underflow when adding/subtracting np.uint8 images.