Who's making small steps in the snow?

Posted by Jonas Sandström on Sat 17 December 2022

My wife pointed out that we had small steps in the snow outside of our living room. It looked like a rat had been running there, but it was hard to know by just looking at the partly snow coverd tracks.

Spoiler alert it was a rat If you are afraid of rats don't look at the picture at the bottom ;)

Since we don't currently have a home security camera in our garden, I took it upon myself to write a small script on my macbook, using its camera to detect changes, and save it as a .jpg. To be honest most of this project was just me googling how to detect motion using opencv-python.

import cv2
import os

# capturing video
capture = cv2.VideoCapture(0)
count = 0
image_path = "...path to folder"
while capture.isOpened():
    # to read frame by frame
    _, img_1 = capture.read()
    _, img_2 = capture.read()

    # find difference between two frames
    try:
        diff = cv2.absdiff(img_1, img_2)

        # to convert the frame to grayscale
        diff_gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)

        # apply some blur to smoothen the frame
        diff_blur = cv2.GaussianBlur(diff_gray, (5, 5), 0)

        # to get the binary image
        _, thresh_bin = cv2.threshold(diff_blur, 10, 255, cv2.THRESH_BINARY)

        # to find contours
        contours, _ = cv2.findContours(thresh_bin, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

        for contour in contours:
            if cv2.contourArea(contour) > 100:
                cv2.imwrite(os.path.join(image_path , "image_%d.jpg" % count), img_2)      
                count += 1
    except:
        # if img_1, img_2 have different length, cv2.absdiff crashes, we ignore this.
        pass

    # end
    if cv2.waitKey(100) == ord("q"):
        exit()


I let the script run during the night and positioned the computers webcam at the spot where we had seen the tracks... Next morning we had the result, not pleasant but at least we know what to deal with now.

rat in snow