import cv2 import os.path import os from PIL import Image ############### # def get_frames(input1) # ex. get_frames(video.mov) # # Task: Extracting frames from a video # # Inputs: # - input1: a video # # Output: # -RGB_avg: a directory with all the frames of the video # # author: Loic Delattre and Maryne Dey (loic.delattre@ecam.fr, maryne.dey@ecam.fr) # date: 06/02/2023 ############### video = 'my_face.mov' def get_frames(vid): path_to_script = os.path.dirname(os.path.abspath(__file__)) if os.path.exists(path_to_script + r"\frames") == False: os.mkdir(path_to_script + r"\frames") # Opens the Video file cap= cv2.VideoCapture(vid) i=0 while cap.isOpened(): ret, img = cap.read() if ret == False: break face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) #detect the face in the frame for (x,y,w,h) in faces: # To draw a rectangle in a face for testing purposes cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,0),2) roi_gray = gray[y:y+h, x:x+w] roi_color = img[y:y+h, x:x+w] eyes = eye_cascade.detectMultiScale(roi_gray) #detect the eyes in the frames taking the face as reference list_ex = [] list_ey = [] list_ew = [] list_eh = [] #To draw a rectangle in eyes for (ex,ey,ew,eh) in eyes: if ew >= 82 and eh >= 82: #cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,127,255),2) list_ex.append(ex) list_ey.append(ey) list_ew.append(ew) list_eh.append(eh) #rectangle on forhead try: fx = min(list_ex) + list_ew[list_ex.index(min(list_ex))] #deducing ROI from the eyes rectangle coordinates fy = max(list_ey) x1 = x + fx x2 = x + fx + 100 #extra values in x and y in the parameters are adjustements made after manual testing y1 = y + fy - 150 y2 = y + fy - 20 imRGB = img[y1:y2, x1:x2] cv2.imwrite('frames/frame'+str(i)+'.jpg',imRGB) i+=1 except: print('error on min value of ex') #cv2.rectangle(roi_color, (fx,fy-150),(fx+100,fy-20),(0,127,255),2) #for testing purposes #cv2.imshow('img',roi_color) #cv2.waitKey(0) cap.release() cv2.destroyAllWindows() return i print('number of frames extracted ' + get_frames(video))