1. 程式人生 > >《python+opencv實踐》一、基於顏色的物體追蹤(下)

《python+opencv實踐》一、基於顏色的物體追蹤(下)

做了功能上的強化,強化如下:

(1)加了pts清空,即當沒有檢測到目標時,清空pts,顯示的影象上不再有軌跡;

(2)加了運動方向判別,能夠判別目標的運動方向及當前座標。

from collections import  deque
import numpy as np
import time
#import imutils
import cv2
#設定紅色閾值,HSV空間
redLower = np.array([170, 100, 100])
redUpper = np.array([179, 255, 255])
#初始化追蹤點的列表
mybuffer = 16
pts = deque(maxlen=mybuffer)
counter = 0
#開啟攝像頭
camera = cv2.VideoCapture(0)
#等待兩秒
time.sleep(3)
#遍歷每一幀,檢測紅色瓶蓋
while True:
    #讀取幀
    (ret, frame) = camera.read()
    #判斷是否成功開啟攝像頭
    if not ret:
        print 'No Camera'
        break
    #frame = imutils.resize(frame, width=600)
    #轉到HSV空間
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    #根據閾值構建掩膜
    mask = cv2.inRange(hsv, redLower, redUpper)
    #腐蝕操作
    mask = cv2.erode(mask, None, iterations=2)
    #膨脹操作,其實先腐蝕再膨脹的效果是開運算,去除噪點
    mask = cv2.dilate(mask, None, iterations=2)
    cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
    #初始化瓶蓋圓形輪廓質心
    center = None
    #如果存在輪廓
    if len(cnts) > 0:
        #找到面積最大的輪廓
        c = max(cnts, key = cv2.contourArea)
        #確定面積最大的輪廓的外接圓
        ((x, y), radius) = cv2.minEnclosingCircle(c)
        #計算輪廓的矩
        M = cv2.moments(c)
        #計算質心
        center = (int(M["m10"]/M["m00"]), int(M["m01"]/M["m00"]))
        #只有當半徑大於10時,才執行畫圖
        if radius > 10:
            cv2.circle(frame, (int(x), int(y)), int(radius), (0, 255, 255), 2)
            cv2.circle(frame, center, 5, (0, 0, 255), -1)
            #把質心新增到pts中,並且是新增到列表左側
            pts.appendleft(center)
    else:#如果影象中沒有檢測到瓶蓋,則清空pts,影象上不顯示軌跡。
        pts.clear()
    
    for i in xrange(1, len(pts)):
        if pts[i - 1] is None or pts[i] is None:
            continue
        #計算所畫小線段的粗細
        thickness = int(np.sqrt(mybuffer / float(i + 1)) * 2.5)
        #畫出小線段
        cv2.line(frame, pts[i - 1], pts[i], (0, 0, 255), thickness)
        #判斷移動方向
        if counter >= 10 and i == 1 and len(pts) >= 10:
            dX = pts[-10][0] - pts[i][0]
            dY = pts[-10][1] - pts[i][1]
            (dirX, dirY) = ("", "")
            
            if np.abs(dX) > 20:
                dirX = "East" if np.sign(dX) == 1 else "West"
            
            if np.abs(dY) > 20:
                dirY = "North" if np.sign(dY) == 1 else "South"
            
            if dirX != "" and dirY != "":
                direction = "{}-{}".format(dirY, dirX)
            else:
                direction = dirX if dirX != "" else dirY
        
            cv2.putText(frame, direction, (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, 
                        (0, 255, 0), 3)
            cv2.putText(frame, "dx: {}, dy: {}".format(dX, dY), (10, frame.shape[0] - 10), 
                        cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)
            
    cv2.imshow('Frame', frame)
    #鍵盤檢測,檢測到esc鍵退出
    k = cv2.waitKey(1)&0xFF
    counter += 1
    if k == 27:
        break
#攝像頭釋放
camera.release()
#銷燬所有視窗
cv2.destroyAllWindows()

由於視訊是映象的,所以圖片上的South-East結果是正確的!