一、环境
win10、Python3.6、OpenCV3.x;编译器:pycharm5.0.3
二、实现目标
根据需要追踪的物体颜色,设定阈值,在视频中框选出需要追踪的物体。
三、实现步骤
1)根据需要追踪的物体颜色,设定颜色阈值,获取追踪物体的掩膜
代码:generate_threshold.py
# -*- coding : utf-8 -*- # Author: Tom Yu import cv2 import numpy as np cap = cv2.VideoCapture(0)#获取摄像头图像 # img = cv2.imread("timg1.jpg") # hsv_img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV) def nothing(x): pass def createbars(): """ 实现创建六个滑块的作用,分别控制H、S、V的最高值与最低值 """ cv2.createTrackbar("H_l","image",0,180,nothing) cv2.createTrackbar("H_h","image",0,180,nothing) cv2.createTrackbar("S_l","image",0,255,nothing) cv2.createTrackbar("S_h","image",0,255,nothing) cv2.createTrackbar("V_l","image",0,255,nothing) cv2.createTrackbar("V_h","image",0,255,nothing) cv2.namedWindow("image") createbars()#创建六个滑块 lower = np.array([0,0,0])#设置初始值 upper = np.array([0,0,0]) while True: ret,frame = cap.read() hsv_frame = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)#将图片由BGR颜色空间转化成HSV空间,HSV可以更好地分割颜色图形 lower[0]=cv2.getTrackbarPos("H_l","image")#获取"H_l"滑块的实时值 upper[0]=cv2.getTrackbarPos("H_h","image")#获取"H_h"滑块的实时值 lower[1]=cv2.getTrackbarPos("S_l","image") upper[1]=cv2.getTrackbarPos("S_h","image") lower[2]=cv2.getTrackbarPos("V_l","image") upper[2]=cv2.getTrackbarPos("V_h","image") mask = cv2.inRange(hsv_frame,lower,upper)#cv2.inrange()函数通过设定的最低、最高阈值获得图像的掩膜 cv2.imshow("img",frame) cv2.imshow("mask",mask) if cv2.waitKey(1)&0xff == 27: break cv2.destroyAllWindows()
实现效果:获取需要追踪的物体颜色阈值
2)根据获取到的阈值,设定阈值范围,在视频中追踪特定颜色的物体并用框选框出所需追踪的物体
代码:tracking_object.py
# -*- coding : utf-8 -*- # Author: Tom Yu import cv2 import numpy as np cap = cv2.VideoCapture(0)#获取摄像头视频 while True: ret,frame = cap.read()#读取每一帧图片 hsv_frame = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)#将每一帧图片转化HSV空间颜色 """ 依据之前的脚本获取的阈值设置最高值与最低值 """ lower = np.array([0,104,205]) upper = np.array([15,208,255]) mask = cv2.inRange(hsv_frame,lower,upper) img,conts,hier = cv2.findContours(mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)#找出边界 cv2.drawContours(frame,conts,-1,(0,255,0),3)#画出边框 dst = cv2.bitwise_and(frame,frame,mask=mask)#对每一帧进行位与操作,获取追踪图像的颜色 #cv2.imshow("mask",mask) #cv2.imshow("dst",dst) cv2.imshow("frame",frame) if cv2.waitKey(1)&0xff == 27: break cv2.destroyAllWindows()
实现效果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。