OpenCV Module 10 : Theo dõi đối tượng

MVT
Đang cập nhật

Video tracking là gì?

Video tracking là quá trình xác định vị trí của một đối tượng chuyển động theo thời gian bằng máy ảnh. Nó có nhiều cách sử dụng, một số trong số đó là: tương tác giữa con người với máy tính, bảo mật và giám sát, giao tiếp và nén video, thực tế tăng cường, kiểm soát giao thông, hình ảnh y tế và chỉnh sửa video

Object Tracking trong computer vison.

Object tracking là một ứng dụng của học sâu trong đó chương trình thực hiện một tập hợp các phát hiện đối tượng ban đầu và phát triển một nhận dạng duy nhất cho từng phát hiện ban đầu và sau đó theo dõi các đối tượng được phát hiện khi chúng di chuyển xung quanh các khung hình trong video.

Tracker Class trong OpenCV

  1. BOOSTING
  2. MIL
  3. KCF
  4. CRST
  5. TLD
    • Tends to recover from occulusions
  6. MEDIANFLOW
    • Good for predictable slow motion
  7. GOTURN
    • Deep Learning based
    • Most Accurate
  8. MOSSE
    • Fastest

Các bước để thực hiện Objects tracking

Step 1 : Download tracking model (chỉ dành cho GOTURN)

if not os.path.isfile('goturn.prototxt') or not os.path.isfile('goturn.caffemodel'):
    print("Downloading GOTURN model zip file")
    urllib.request.urlretrieve('https://www.dropbox.com/sh/77frbrkmf9ojfm6/AACgY7-wSfj-LIyYcOgUSZ0Ua?dl=1', 'GOTURN.zip')

    # Giải nén file
        !unzip GOTURN.zip

    # Sau khi giải nén xong, ta xóa file
    os.remove('GOTURN.zip')

Step 2: Import những thư viện có liên quan

import numpy as np
import matplotlib.pyplot as plt
import cv2
import math
import glob
import sys
import os
import matplotlib.animation as FuncAnimation
from IPython.display import HTML 
import urllib

Step 3: Viết một số hàm có thể tái sử dụng nhiều lần giúp cho code trở nên clean hơn.

def draw_rectange(frame, bbox) : 
    pt1 = (int(bbox[0]), int(bbox[1]))
    pt2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
    cv2.rectangle(frame, pt1, pt2, (0,0,255), 3)

def display_rectange(frame, bbox) : 
    frame_copy = frame.copy() 
    plt.figure(figsize=(20,10))
    draw_rectange(frame_copy, bbox)
    plt.imshow(frame_copy);plt.axis(False);
def draw_text(frame, text, location, color=(12, 96, 232)):
    cv2.putText(frame, text, location, cv2.FONT_HERSHEY_SIMPLEX, 1, color, 3)

Step 4: Render ảnh trải nghiệm trước khi bắt đầu code

HTML("""
    <video controls width="800" height="600">
        <source src="race_car.mp4" />
    </video>
""")

Step 5: Viết function lựa chọn loại tracker

def create_select_tracker_type() : 
    tracker_types = ["BOOSTING", "MIL", "KCF", "CSRF", "TLD", "MEDIAFLOW", "GOTURN", "MOSSE"]
    print("What tracker type would you like to select?")
    print("Enter 1 for BOOSTING")
    print("Enter 2 for MIL")
    print("Enter 3 for KCF")
    print("Enter 4 for CSRF")
    print("Enter 5 for TLD")
    print("Enter 6 for MEDIAFLOW")
    print("Enter 7 for GOTURN")
    print("Enter 8 for MOSSE")
    choice = input("Enter your type here: ")

    if choice == "1" : 
        tracker = cv2.legacy_TrackerBoosting.create()
    elif choice == "2" : 
        tracker = cv2.TrackerMIL_create()
    elif choice == "3" : 
        tracker = cv2.TrackerKCF_create()
    elif choice == "4" : 
        tracker = cv2.TrackerCSRT_create()
    elif choice == "5" : 
        tracker = cv2.legacy_TrackerTLD.create()
    elif choice == "6" : 
        tracker = cv2.legacy_TrackerMedianFlow.create()
    elif choice == "7" : 
        tracker = cv2.legacy_TrackerMedianFlow.create() 
    elif choice == "8" : 
        tracker = cv2.TrackerGOTURN_create()
    else : 
        tracker = cv2.legacy_TrackerMOSSE.create()

    return tracker_types[int(choice)-1], tracker

Step 6: Bắt đầu xử lý lập trình và ghi trình theo dõi để xuất hình ảnh

source = "race_car.mp4"

video = cv2.VideoCapture(source)

if not video.isOpened(): 
    print("Could not open video");
    sys.exit()
else : 
    width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))

tracker_type, tracker = create_select_tracker_type()

video_output_filename = f"race_car_tracking_{tracker_type}.mp4"
video_out = cv2.VideoWriter(video_output_filename,cv2.VideoWriter_fourcc(*"avc1"), 27, (width, height))

ret, frame = video.read()

roi = cv2.selectROI(frame,False)

draw_rectange(frame, roi)

tracker.init(frame, roi)

while True : 
    ret, frame = video.read() 
    if not ret : 
        break

    # Start timer
    timer = cv2.getTickCount()
    # Calc FPS
    FPS = cv2.getTickFrequency() / (cv2.getTickCount() - timer) / 10000
    # Update tracker 
    ok, bbox = tracker.update(frame)

    if ok : 
        draw_rectange(frame, bbox)
    else : 
        draw_text(frame, "Tracking Failure detected", (80,140), (255,0,0))
    draw_text(frame, tracker_type, (80,60))
    draw_text(frame, "FPS: " + str(int(FPS)), (80,100) )

    video_out.write(frame)
video_out.release()
video.release()
cv2.destroyAllWindows()

Before starting to write video, you need to Enter an number which represent for type of somewhat method and draw an rectangle to object you want, then type enter to start write tracker to video.

What tracker type would you like to select?
Enter 1 for BOOSTING
Enter 2 for MIL
Enter 3 for KCF
Enter 4 for CSRF
Enter 5 for TLD
Enter 6 for MEDIAFLOW
Enter 7 for GOTURN
Enter 8 for MOSSE
Enter your type here: 8

Step 7: Trải nghiệm Tracked Video đã được lưu từ bước trên

Sử dụng code dưới để thử nghiệm:

Giả sử, bạn chọn phương pháp theo dõi GOTURN đã được lưu trong máy tính của bạn.

HTML("""
    <video controls width="800" height="600">
        <source src="race_car_tracking__GOTURN.mp4"/>
    </video>
""")

Bài viết có liên quan