opencv的目標跟蹤演算法

markriver發表於2021-09-09

opencv的目標跟蹤演算法(OpenCV Object Tracking)

今日拜讀Adrian Rosebrock的大作,看到了有關OpenCV Object Tracking的演算法介紹,寫了程式碼跑了一下,果然很神奇!,特別做了筆記學習一下,分享給大家.


圖片描述

trace.png


圖片描述

opencv_object_tracking.gif


這篇文章所講述的目標跟蹤是採用opencv的演算法實現的,並非當下流行的深度學習的object detect.
經測試,效果還不錯,效率也很高,在我的老款mac air上跑起來也非常流暢,令我印象深刻.

其實目標追蹤演算法的確很多,目前最新的opencv(3.4.2)上就有8種object tracking演算法.

  1. BOOSTING Tracker: Based on the same algorithm used to power the machine learning behind Haar cascades (AdaBoost), but like Haar cascades, is over a decade old. This tracker is slow and doesn’t work very well. Interesting only for legacy reasons and comparing other algorithms. (minimum OpenCV 3.0.0)

  2. MIL Tracker: Better accuracy than BOOSTING tracker but does a poor job of reporting failure. (minimum OpenCV 3.0.0)

  3. KCF Tracker: Kernelized Correlation Filters. Faster than BOOSTING and MIL. Similar to MIL and KCF, does not handle full occlusion well. (minimum OpenCV 3.1.0)

  4. CSRT Tracker: Discriminative Correlation Filter (with Channel and Spatial Reliability). Tends to be more accurate than KCF but slightly slower. (minimum OpenCV 3.4.2)

  5. MedianFlow Tracker: Does a nice job reporting failures; however, if there is too large of a jump in motion, such as fast moving objects, or objects that change quickly in their appearance, the model will fail. (minimum OpenCV 3.0.0)

  6. TLD Tracker: I’m not sure if there is a problem with the OpenCV implementation of the TLD tracker or the actual algorithm itself, but the TLD tracker was incredibly prone to false-positives. I do not recommend using this OpenCV object tracker. (minimum OpenCV 3.0.0)

  7. MOSSE Tracker: Very, very fast. Not as accurate as CSRT or KCF but a good choice if you need pure speed. (minimum OpenCV 3.4.1)

  8. GOTURN Tracker: The only deep learning-based object detector included in OpenCV. It requires additional model files to run (will not be covered in this post). My initial experiments showed it was a bit of a pain to use even though it reportedly handles viewing changes well (my initial experiments didn’t confirm this though). I’ll try to cover it in a future post, but in the meantime, take a look at Satya’s writeup. (minimum OpenCV 3.2.0)

其中比較出色的就是 CSRT和KCF.(注意CSRT只有最新版才支援哦)

文章建議如下:

  • 使用CSRT: 當需要更高的準確率的時候採用,這個更耗時一點.

  • 使用KCF: 這個更加高速(幀),單準確率差一點.

  • 使用MOSSE: 只最求高速的話,就選它吧.

完整程式碼如下:

from imutils.video import VideoStreamfrom imutils.video import FPSimport argparseimport imutilsimport timeimport cv2

ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video", type=str,
                help="path to input video file")
ap.add_argument("-t", "--tracker", type=str, default="kcf",
                help="OpenCV object tracker type")
args = vars(ap.parse_args())

(major, minor) = cv2.__version__.split(".")[:2]if int(major) == 3 and int(minor) < 3:
    tracker = cv2.Tracker_create(args["tracker"].upper())else:
    OPENCV_OBJECT_TRACKERS = {        "csrt": cv2.TrackerCSRT_create,        "kcf": cv2.TrackerKCF_create,        "boosting": cv2.TrackerBoosting_create,        "mil": cv2.TrackerMIL_create,        "tld": cv2.TrackerTLD_create,        "medianflow": cv2.TrackerMedianFlow_create,        "mosse": cv2.TrackerMOSSE_create
    }


    tracker = OPENCV_OBJECT_TRACKERS[args["tracker"]]()

initBB = Noneif not args.get("video", False):
    print("[INFO] starting video stream...")
    vs = VideoStream(src=0).start()
    time.sleep(1.0)else:
    vs = cv2.VideoCapture(args["video"])

fps = Nonewhile True:
    frame = vs.read()
    frame = frame[1] if args.get("video", False) else frame    if frame is None:        break
    frame = imutils.resize(frame, width=800)
    (H, W) = frame.shape[:2]    if initBB is not None:
        (success, box) = tracker.update(frame)        if success:
            (x, y, w, h) = [int(v) for v in box]
            cv2.rectangle(frame, (x, y), (x + w, y + h),
                          (0, 255, 0), 2)
        fps.update()
        fps.stop()

        info = [
            ("Tracker", args["tracker"]),
            ("Success", "Yes" if success else "No"),
            ("FPS", "{:.2f}".format(fps.fps())),
        ]        for (i, (k, v)) in enumerate(info):
            text = "{}: {}".format(k, v)
            cv2.putText(frame, text, (10, H - ((i * 20) + 20)),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1) & 0xFF

    if key == ord("s"):
        initBB = cv2.selectROI("Frame", frame, fromCenter=False,
                               showCrosshair=True)
       tracker.init(frame, initBB)
        fps = FPS().start()        elif key == ord("q"):        breakif not args.get("video", False):
    vs.stop()else:
    vs.release()

cv2.destroyAllWindows()

使用了例子提供的影片檔案,效果如下:


圖片描述

opencv_object_tracking.gif

圖片描述

opencv_object_tracking_selection.gif



作者:gaoshine
連結:


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/818/viewspace-2819350/,如需轉載,請註明出處,否則將追究法律責任。

相關文章