opencv目标追踪

参考https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_colorspaces/py_colorspaces.html#converting-colorspaces

原理如下:

使用opencv进行视频捕捉,然后将RGB图像转为HSV图像,根据颜色范围找出特定颜色,从而实现对这个目标的追踪

代码如下:

# coding: utf-8
import cv2 as cv
import numpy as np

if __name__ == "__main__":
    # print all colors
    flags = [i for i in dir(cv) if i.startswith("COLOR_")]
    print flags

    ### Object tracking ###
    # open device
    cap = cv.VideoCapture(0)
    # set blue range in HSV mode
    lower_blue = np.array([110, 50, 50])
    upper_blue = np.array([130, 255, 255])
    # start capture and tracking color
    while True:
        # capture one frame
        ret, frame = cap.read()
        # do simple proccessing
        hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)      # RGB->HSV
        mask = cv.inRange(hsv, lower_blue, upper_blue)  # set mask for HSV image
        res = cv.bitwise_and(frame, frame, mask=mask)   # do bitwise-and mask
        # show image
        cv.imshow("frame", frame)
        cv.imshow("hsv", hsv)
        cv.imshow("mask", mask)
        cv.imshow("res", res)
        # judge exit
        if cv.waitKey(5) & 0xff == 27:
            break
    # release all
    cv.destroyAllWindows()

效果如下:

使用手机显示蓝色图片,使用程序进行追踪

opencv目标追踪_第1张图片

你可能感兴趣的:(opencv入门)