python_opencv颜色检测加自动跟踪

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


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值