这篇教程通过OpenCV实现对指定颜色的物体追踪写得很实用,希望能帮到您。 本文实现对特定颜色的物体追踪,我实验用的是绿萝的树叶。 新建脚本ball_tracking.py,加入代码: import argparsefrom collections import dequeimport cv2import numpy as np 导入必要的包,然后定义一些函数 def grab_contours(cnts): # 如果 cv2.findContours 返回的轮廓元组的长度为“2”,那么我们使用的是 OpenCV v2.4、v4-beta 或 v4-official if len(cnts) == 2: cnts = cnts[0] # 如果轮廓元组的长度为“3”,那么我们使用的是 OpenCV v3、v4-pre 或 v4-alpha elif len(cnts) == 3: cnts = cnts[1] else: raise Exception(("Contours tuple must have length 2 or 3, " "otherwise OpenCV changed their cv2.findContours return " "signature yet again. Refer to OpenCV's documentation " "in that case")) return cntsdef resize(image, width=None, height=None, inter=cv2.INTER_AREA): dim = None (h, w) = image.shape[:2] # 如果高和宽为None则直接返回 if width is None and height is None: return image # 检查宽是否是None if width is None: # 计算高度的比例并并按照比例计算宽度 r = height / float(h) dim = (int(w * r), height) # 高为None else: # 计算宽度比例,并计算高度 r = width / float(w) dim = (width, int(h * r)) resized = cv2.resize(image, dim, interpolation=inter) # return the resized image return resized grab_contours 对于opencv不同版本做了兼容处理。 resize等比例改变图片的大小。 命令行参数ap = argparse.ArgumentParser()ap.add_argument("-v", "--video", help="path to video")ap.add_argument("-b", "--buffer", type=int, default=64, help="max buffer size")args = vars(ap.parse_args())# 绿色树叶的HSV色域空间范围greenLower = (29, 86, 6)greenUpper = (64, 255, 255)pts = deque(maxlen=args["buffer"])vs = cv2.VideoCapture(0)fps = 30 #保存视频的FPS,可以适当调整size=(600,450)fourcc=cv2.VideoWriter_fourcc(*'XVID')videowrite=cv2.VideoWriter('output.avi',fourcc,fps,size) 定义参数 通过python-turtle库实现绘制图画 Python实现图片和视频的相互转换
|