Challenge

Project 8

#OBJECTIVE:  To perform sparse optical flow with Lucas Kanade optical flow model for the pixels of interest 
#which are derived from Shi-Tomashi corner detection algorithm.

# Import the required libraries
import cv2
import numpy as np

# tracking features. Identifying corners through shi-tomasi corner detector method
# cv2.goodFeaturesToTrack opencv function is used find the features using Shi-Tomasi corner detector algorithm 
def find_features(gray_images):
    points = cv2.goodFeaturesToTrack(gray_images,mask = None, maxCorners = 100,qualityLevel = 0.2,minDistance = 10,blockSize = 7)
    
    return points


#Lucas Kanade sparse optical flow model
def LK_model(gray_t_1,gray_t,prev_points):
    points,status,error = cv2.calcOpticalFlowPyrLK(gray_t_1,gray_t,prev_points,None,winSize = (20,20),maxLevel=2,criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.04))
    
    return (points,status,error)


#driver script
capture = cv2.VideoCapture("traffic.mp4") 
#lk_params = dict(winSize=(15,15),maxLevel=2,criteria=(cv2.TERM_CRITERIA_EPS|cv2.TERM_CRITERIA_COUNT,10,0.03))
color = np.random.randint(0,255,(100,3))       
ret,prev_frame = capture.read()                

prev_gray= cv2.cvtColor(prev_frame,cv2.COLOR_BGR2GRAY)        
prev_points = find_features(prev_gray)                  
mask_image = np.zeros_like(prev_frame)         
output_frames = []

#reading further frames
while(True):
    
    ret,frame = capture.read()   
                
    #Terminate when no frame is detected
    if not ret:
        break         
    
    current_gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)         
    current_points,status,error = LK_model(prev_gray,current_gray,prev_points)    
    
    
    #extracting successful points
    if current_points is not None: 
        current_points = current_points[status ==1]                
        old_points = prev_points[status==1]
        
    #performing mapping
    for i, (current,prev) in enumerate(zip(current_points,old_points)):    
        a,b = current.ravel()
        c,d = prev.ravel()
        
        #creating black screen where lines are drawn from a-d to track the flow of the pixels
        mask_image = cv2.line(mask_image,(int(a),int(b)),(int(c),int(d)),color[i].tolist(),2) 
        
       # Draw a circle for each current point
        frame = cv2.circle(frame,(int(a),int(b)),5,color[i].tolist(),-1)   
        
    
    img = cv2.add(frame,mask_image)       
    #image = frame
    
    cv2.imshow('Traffic Flow Frame',img)              
    output_frames.append(img)
    #cv2.imshow('mask image',mask_image)
    #cv2.imshow('mask image',image)
    
    k = cv2.waitKey(5)
    if k ==27:             
        break
    
    #set the current frame as the t-1 frame and update the current points at the prvious points (t-1). Basically updating the frame
    prev_gray = current_gray.copy()       
    prev_points = current_points.reshape(-1,1,2)        
    
capture.release()                 

cv2.destroyAllWindows()           

height,width,_ = img.shape         
size = (width,height)              

# Creating object for appending to the video
output = cv2.VideoWriter('Traffic_Optical_Flow.mp4',cv2.VideoWriter_fourcc('F','M','P','4'), 30, size)

# Writing the video by repeating through each frame
for image in output_frames:
    output.write(image)

Week8_Task

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.