# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# ### Import Libraries

# +
import cv2
import numpy as np

cap = cv2.VideoCapture(0)
_,frame = cap.read()
frame = cv2.flip(frame,1)
face_casc =cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
face_rects = face_casc.detectMultiScale(frame)
face_x,face_y,w,h=tuple(face_rects[0])
track_window = (face_x,face_y,w,h)
roi = frame[face_y:face_y+h,face_x:face_y+w]
hsv_roi = cv2.cvtColor(roi,cv2.COLOR_BGR2HSV)
# -

# ### Histogram to target on each frame for the meanshift calculation

roi_hist = cv2.calcHist([hsv_roi],[0],None,[180],[0,180])

# ### Normalize the histogram

cv2.normalize(roi_hist,roi_hist,0,255,cv2.NORM_MINMAX);

# ### Set the termination criteria
# 10 iterations or move 1 pt

term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT,10 ,1)

# ### It's a Kind of Magic

# +
# While loop
while True:

    # capture video
    _,frame= cap.read()
    frame = cv2.flip(frame,1)
    # if statement
    if _ == True:
    
        # Frame in HSV
        hsv =  cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
        
        # Calculate the base of ROI
        dest_roi = cv2.calcBackProject([hsv],[0],roi_hist,[0,180],1)
        
        # Meanshift to get the new coordinates of rectangle
        _,track_window = cv2.meanShift(dest_roi,track_window,term_crit)
        
        # Draw new rectangle on image
        x,y,w,h = track_window
        
        # Open new window and display
        img2 = cv2.rectangle(frame,(x,y),(x+w,y+h),(255,255,0),2)
        
        cv2.imshow("FACE TRACKER",img2)
        # Close window
        if cv2.waitKey(300) & 0xFF == ord("q"):
            break
        
    # else statement
    else:
        break
    
# Release and Destroy
cap.release()
cv2.destroyAllWindows()



StarcoderdataJupyterScriptsDedupFiltered