[转]《python+opencv实践》一、基于颜色的物体追踪(下)

新的改变

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

(1)加了pts清空,即当没有检测到目标时,清空pts,显示的图像上不再有轨迹;

(2)加了运动方向判别,能够判别目标的运动方向及当前坐标。

代码

#  coding: utf-8
#!/usr/bin/env python
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()
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用PythonOpenCV进行物体追踪,你需要进行以下步骤: 1. 安装OpenCV库。 2. 捕获视频流或打开视频文件。 3. 选择要追踪的对象并提取其颜色范围。 4. 对每一帧进行处理,将颜色范围内的像素标记为白色,其余像素标记为黑色。 5. 对二值图像应用形态学运算,例如膨胀腐蚀,以去除噪声和填充空洞。 6. 使用轮廓检测算法检测对象的轮廓。 7. 根据轮廓的中心点和边界框计算对象的位置和大小。 8. 在视频帧上绘制对象的边界框和中心点。 以下是一个简单的物体追踪示例代码: ```python import cv2 cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() if not ret: break hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # 设置颜色范围 low_color = (0, 100, 100) high_color = (10, 255, 255) # 创建掩膜 mask = cv2.inRange(hsv_frame, low_color, high_color) # 进行形态学运算 kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) mask = cv2.erode(mask, kernel, iterations=2) mask = cv2.dilate(mask, kernel, iterations=2) # 检测轮廓 contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 如果有轮廓,找到最大轮廓并计算其中心点和边界框 if contours: max_contour = max(contours, key=cv2.contourArea) x, y, w, h = cv2.boundingRect(max_contour) center = (x + w // 2, y + h // 2) # 绘制边界框和中心点 cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.circle(frame, center, 5, (0, 0, 255), -1) cv2.imshow('Frame', frame) if cv2.waitKey(10) == ord('q'): break cap.release() cv2.destroyAllWindows() ``` 这段代码可以从摄像头捕获视频流,并追踪红色对象。你可以根据需要调整颜色范围和形态学运算参数来适应不同的应用场景。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值