<reponame>Aasish4/Optical-flow-OpenCV
# -*- coding: utf-8 -*-
"""lucas_kanade.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1O6PF6SF1IPFZU_YEdFgAR-XiGGxpHBSU
"""

import cv2
import numpy as np
from google.colab.patches import cv2_imshow

def lucas_kanade(video_path):
  cap = cv2.VideoCapture(video_path)

  # params for ShiTomasi corner detection
  feature_params = dict(maxCorners=100, qualityLevel=0.3, minDistance=7, blockSize=7)

  # params for lucas kanade optical flow
  lk_params = dict(winSize=(15,15), maxLevel=2, criteria=(cv2.TERM_CRITERIA_COUNT,10,0.03))

  # random color generation
  color = np.random.randint(0,255,(100,3))

  # Take first frame for corner detection
  ret, first_frame = cap.read()
  gray_first = cv2.cvtColor(first_frame, cv2.COLOR_BGR2GRAY)
  p0 = cv2.goodFeaturesToTrack(gray_first, mask=None, **feature_params)

  # Create a mask for drawing
  mask = np.zeros_like(first_frame)

  frame_width = int(cap.get(3))
  frame_height = int(cap.get(4))

  size = (frame_width, frame_height)

  name = f'{video_path}'.split('/')[-1].split('.')[-2]+'_out.avi'

  # initilize the video codec
  result = cv2.VideoWriter(name,  
                         cv2.VideoWriter_fourcc(*'MJPG'), 
                         10, size) 

  while True:
    ret, frame = cap.read()
    if not ret:
      break
    gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Calculate the optical flow
    p1, st, err = cv2.calcOpticalFlowPyrLK(
        gray_first, gray_frame, p0, None, **lk_params
    )

    # select good points
    good_new = p1[st == 1]
    good_old = p0[st == 1]

    # draw the tracks
    for i, (new, old) in enumerate(zip(good_new, good_old)):
      a, b = new.ravel()
      c, d = old.ravel()

      mask = cv2.line(mask, (a,b), (c,d), color[i].tolist(), 2)
      frame = cv2.circle(frame,  (a,b), 5, color[i].tolist(), -1)
    img = cv2.add(frame, mask)
    result.write(img)
    k = cv2.waitKey(25) & 0xFF
    if k == 27:
      break
    if k == ord('c'):
      mask.np.zeros_like(first_frame)
    gray_first = gray_frame.copy()
    p1 = good_new.reshape(-1,1,2)
# -*- coding: utf-8 -*-
"""lucas_kanade.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1O6PF6SF1IPFZU_YEdFgAR-XiGGxpHBSU
"""

import cv2
import numpy as np
from google.colab.patches import cv2_imshow

def lucas_kanade(video_path):
  cap = cv2.VideoCapture(video_path)

  # params for ShiTomasi corner detection
  feature_params = dict(maxCorners=100, qualityLevel=0.3, minDistance=7, blockSize=7)

  # params for lucas kanade optical flow
  lk_params = dict(winSize=(15,15), maxLevel=2, criteria=(cv2.TERM_CRITERIA_COUNT,10,0.03))

  # random color generation
  color = np.random.randint(0,255,(100,3))

  # Take first frame for corner detection
  ret, first_frame = cap.read()
  gray_first = cv2.cvtColor(first_frame, cv2.COLOR_BGR2GRAY)
  p0 = cv2.goodFeaturesToTrack(gray_first, mask=None, **feature_params)

  # Create a mask for drawing
  mask = np.zeros_like(first_frame)

  frame_width = int(cap.get(3))
  frame_height = int(cap.get(4))

  size = (frame_width, frame_height)

  name = f'{video_path}'.split('/')[-1].split('.')[-2]+'_out.avi'

  # initilize the video codec
  result = cv2.VideoWriter(name,  
                         cv2.VideoWriter_fourcc(*'MJPG'), 
                         10, size) 

  while True:
    ret, frame = cap.read()
    if not ret:
      break
    gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Calculate the optical flow
    p1, st, err = cv2.calcOpticalFlowPyrLK(
        gray_first, gray_frame, p0, None, **lk_params
    )

    # select good points
    good_new = p1[st == 1]
    good_old = p0[st == 1]

    # draw the tracks
    for i, (new, old) in enumerate(zip(good_new, good_old)):
      a, b = new.ravel()
      c, d = old.ravel()

      mask = cv2.line(mask, (a,b), (c,d), color[i].tolist(), 2)
      frame = cv2.circle(frame,  (a,b), 5, color[i].tolist(), -1)
    img = cv2.add(frame, mask)
    result.write(img)
    k = cv2.waitKey(25) & 0xFF
    if k == 27:
      break
    if k == ord('c'):
      mask.np.zeros_like(first_frame)
    gray_first = gray_frame.copy()
    p1 = good_new.reshape(-1,1,2)
# -*- coding: utf-8 -*- lucas_kanade.ipynb  Automatically generated by Colaboratory.  Original file is located at     https://colab.research.google.com/drive/1O6PF6SF1IPFZU_YEdFgAR-XiGGxpHBSU # params for ShiTomasi corner detection # params for lucas kanade optical flow # random color generation # Take first frame for corner detection # Create a mask for drawing # initilize the video codec # Calculate the optical flow # select good points # draw the tracks