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) # 这个是彩图
contours, hierarchy = cv2.findContours(mask3, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 只检测外侧轮廓
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_SIMPLEX, 0.75, (50, 170, 50), 2)
cv2.imshow("Tracking", frame)
k = cv2.waitKey(1) & 0xff
if k == 27 : break
python_opencv颜色检测加自动跟踪
最新推荐文章于 2023-11-29 22:58:30 发布