Search code examples
pythonopencvhaar-classifier

Recording x/y axis movement with openCV-python


I'm trying to record the distance travelled by an object (in this instance, part of a face as detected by a haar cascade) from a video file. So far, I have a rectangle drawn to the section of the face that I wish to record x/y travel data for, but have been unable to find info on exactly how to store info on how far/which way the face has travelled in 2 dimensions. My code is below:

import cv2
import numpy as py
from matplotlib import pyplot as plt 

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture("resources/video/EXAMPLE.mp4")

while True:
    ret, img = cap.read()
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 9)
    for (x,y,w,h) in faces:
        cv2.rectangle(img, (x,y), (x+w, int(y+h/3)), (255,0,0), 2)


    cv2.imshow('img',img)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

cap.release()
cap.destroyAllWindows()

Any info/pointers as far as how I can record movement data would be appreciated!


Solution

  • If you simply want to store the coordinates, you can add the (x,y) tuple to a list

    If you're tracking just one face you could use object tracking

    If you want to track multiple faces you can check out the multitracker.