功能实现:基于Opencv的颜色追踪

编程语言:python

IDE:pycharm

代码实现(以追踪绿色为例):

import cv2 as cv
import numpy as np

cap = cv.VideoCapture(0)

fps = 30.0  # 视频帧率
fourcc = cv.VideoWriter_fourcc('M', 'J', 'P', 'G')
videoWriter = cv.VideoWriter('color_track.avi', fourcc, fps, (640*2, 480))

while True:
    ret,frame = cap.read()
    cv.imshow("img", frame)

    hsv = cv.cvtColor(frame,cv.COLOR_BGR2HSV)

    # 指定绿色范围
    lowerb = np.array([35,43,46])
    upperb = np.array([77,255,255])

    # 截取绿色目标
    mask = cv.inRange(hsv,lowerb,upperb)
    cv.imshow("mask", mask)

    # 形态学操作:开操作(去除mask中的细小颗粒)
    kernel = cv.getStructuringElement(cv.MORPH_RECT,(5,5))
    mask_open = cv.morphologyEx(mask,cv.MORPH_OPEN,kernel,iterations=2)

    # 还原目标像素
    dst = cv.bitwise_and(frame,frame,mask=mask_open)
    cv.imshow("dst", dst)

    # 图像拼接:axis=0 纵向拼接;axis=1 横向拼接
    result = np.concatenate([frame, dst],1)
    cv.imshow("result", result)

    # 保存视频
    videoWriter.write(result)

    c = cv.waitKey(50)
    if c == 27:
        break
videoWriter.release()
cap.release()

实现效果(视频上传不了,以图片表示吧):

 

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐