python opencv顏色檢測加自動跟蹤

2021-10-19 18:50:31 字數 2323 閱讀 6013

import cv2

import numpy as np

''''''

tracker = cv2.trackerkcf_create()

video = cv2.videocapture(0)

kernel = cv2.getstructuringelement(cv2.morph_rect, (3, 3))

''''''

def roi_select(frame,):

# 將影象轉換到 hsv 空間

hsv = cv2.cvtcolor(frame, cv2.color_bgr2hsv)

# 設定 hsv 閾值到藍色範圍。

lower_blue = np.array([0, 80, 50]) # 最低

upper_blue = np.array([0, 255, 255]) # 最高

# 設定閾值影象中只出現藍色範圍的物件

mask = cv2.inrange(hsv, lower_blue, upper_blue)

mask2 = cv2.morphologyex(mask, cv2.morph_open, kernel)

mask3 = cv2.morphologyex(mask2, cv2.morph_close, kernel)

#res = cv2.bitwise_and(frame, frame, mask=mask3) # 這個是彩圖

maxarea = 0

maxindex = 0

for i, c in enumerate(contours):

area = cv2.contourarea(c)

if area > maxarea:

maxarea = area

maxindex = i

# cv2.drawcontours(frame1, contours, maxindex, (0, 0, 255), 3)

'''''' # 獲取外切矩形

if len(contours):

x, y, w, h = cv2.boundingrect(contours[maxindex])

cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)

# 獲取中心畫素點

center_x = int(x + w / 2)

center_y = int(y + h / 2)

cv2.circle(frame, (center_x, center_y), 5, (0, 0, 255), -1)

return (x,y,w,h)

while true:

k,frame = video.read()

cv2.imshow("tracking",frame)

k = cv2.waitkey(30) & 0xff

if k == 27:

break

bbox = roi_select(frame)

'''第乙個值為矩形框中最小的x值 -列

第二個值為矩形框中最小的y值 —行

第三個值為這個矩形框的寬 -列

第四個值為這個矩形框的高 -行

'''ok = tracker.init(frame, bbox)

#cv2.destroywindow("roi selector")

while

true

: ok, frame = video.read(

) ok, bbox = tracker.update(frame)

if ok:

p1 =

(int

(bbox[0]

),int(bbox[1]

))p2 =

(int

(bbox[0]

+ bbox[2]

),int(bbox[1]

+ bbox[3]

))cv2.rectangle(frame, p1, p2,(0

,0,255),

2,2)

cv2.puttext(frame,

'kcf'

,(bbox[0]

,bbox[1]

-5),cv2.font_hershey_******x,

0.75,(

50,170,50)

,2) cv2.imshow(

"tracking"

, frame)

k = cv2.waitkey(1)

&0xff

if k ==27:

break

Python OpenCV實現簡單的人臉檢測

匯入opencv庫 import cv2 載入特徵分類器 opencv自帶 face cascade cv2.cascadeclassifier haarcascade frontalface default.xml 開啟電腦攝像頭 capture cv2.videocapture 0 獲得攝像頭捕...

python opencv實現人臉和眼睛檢測

coding utf8 import cv2 import time defdetect 定義乙個檢測函式 face cascade cv2.cascadeclassifier d program files opencv opencv sources data haarcascades haarc...

python opencv 更改顏色空間

色彩轉換,我們使用函式cv2.cvtcolor input image,flag 這裡flag決定轉換的型別 import numpy as np import cv2 對於bgr gray轉換我們使用標誌位 cv2.color bgr2gray。而對bgr hsv來說類似,我們使用cv2.colo...