不規則區域的矩,表示把一個歸一化的灰度級圖像函數理解為一個二維隨機變量的概率密度,這個隨機變量的屬性可以用統計特徵--矩(Moments)來描述。通過假設非零的像素值表示區域,矩可以用於二值或灰度級的區域描述
M pq = sigma(i)sigma(j) i p j q f(i,j)
其中x,y,i,j是區域點的坐標(在數字圖像中的像素坐標)。
令Xc,Yc表示區域重心的坐標,則:
Xc = M 10 /M 00 ;
Yc = M 01 /M 00 ;
import cv2 import numpy as np def track(frame): # Convert BGR to HSV hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) cv2.imshow('hsv',hsv) # define range of blue color in HSV lower_blue = np.array([110,50,50]) upper_blue = np.array([130,255,255]) # Threshold the HSV image to get only blue colors mask = cv2.inRange(hsv, lower_blue, upper_blue) moments = cv2.moments(mask) m00 = moments['m00'] centroid_x, centroid_y = None, None if m00 != 0: centroid_x = int(moments['m10']/m00)#Take X coordinate centroid_y = int(moments['m01']/m00)#Take Y coordinate print 'x=',centroid_x, print 'y=',centroid_y ctr = (-1,-1) if centroid_x != None and centroid_y !=None: ctr = (centroid_x, centroid_y) # Put black circle in at centroid in image cv2.circle(frame, ctr, 15, (0,0,255)) # Bitwise-AND mask and original image res = cv2.bitwise_and(frame,frame, mask= mask) #cv2.imshow('mask',mask) #cv2.imshow('res',res) cv2.imshow('frame',frame) return ctr #cv2.destroyAllWindows() if __name__ == '__main__': cap = cv2.VideoCapture(0) while True: # Take each frame _, frame = cap.read() track(frame) if cv2.waitKey(1) & 0xFF == 27: break參考資料: http://blog.csdn.net/fengbingchun/article/details/6938895
No comments:
Post a Comment