OpenCV3-Python简单移动目标跟踪
admin 于 2018年09月11日 发表在 计算机视觉

目标跟踪是计算机视觉中的一个重要研究方向,有着广泛的应用,如:视频监控,无人驾驶等。

本文介绍的目标跟踪方法,即通过Opencv-Python中的图像处理方法,实现对摄像头视频中移动目标的简单定位,并进行后续处理。

1. 运动目标跟踪

实现当摄像头中物体移动时,绘制对应的区域的边界框,并进行跟踪检测。

import cv2
import numpy as np
getStructuringElement
camera = cv2.VideoCapture(0)

'''
cv2.getStructuringElement(shape, ksize[, anchor]) → retval
Returns a structuring element of the specified size and shape for morphological operations.

Parameters:	
shape – Element shape that could be one of the following:
    (1) MORPH_RECT - a rectangular structuring element:
    (2)MORPH_ELLIPSE - an elliptic structuring element, that is, a filled ellipse inscribed into the rectangle Rect(0, 0, esize.width, 0.esize.height)
    (3) MORPH_CROSS - a cross-shaped structuring element
    (4)CV_SHAPE_CUSTOM - custom structuring element (OpenCV 1.x API)
ksize – Size of the structuring element.
'''
es = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (10,10))
kernel = np.ones((5,5),np.uint8)
background = None

while (True):
  ret, frame = camera.read()    #读取一帧太虚想
  if background is None:
    background = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    background = cv2.GaussianBlur(background, (21, 21), 0)
    continue

  #将帧转换为灰阶
  gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  
  '''
  对灰度图像进行高斯模糊处理
  实际应用中,每个输入的视频都会因自然振动、光照变化或摄像头本身等原因产生噪声。平滑处理能减少在运动和跟踪时产生的噪声
  '''
  gray_frame = cv2.GaussianBlur(gray_frame, (21, 21), 0)
  
  #完成对帧的灰度转换和平滑后,就可计算与背景帧的差异,并获取一个差分图
  diff = cv2.absdiff(background, gray_frame)
  
  #利用阈值来获取黑白图像
  diff = cv2.threshold(diff, 80, 255, cv2.THRESH_BINARY)[1]
  
  #通过膨胀(dilate),对孔和缺陷进一步处理
  diff = cv2.dilate(diff, es, iterations = 2)
  
  #获取图像中的目标轮廓
  image, cnts, hierarchy = cv2.findContours(diff.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  
  #给目标轮廓绘制对应的边界框
  for c in cnts:
    if cv2.contourArea(c) < 1500:
      continue
    (x, y, w, h) = cv2.boundingRect(c)
    cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 255, 0), 2)
  
  #显示图像
  cv2.imshow("contours", frame)
  cv2.imshow("dif", diff)
  if cv2.waitKey(100) & 0xff == ord("q"):
      break

camera.release()
cv2.destroyAllWindows()

2. 实验结果

对于简单目标,该跟踪结果相当准确,但是,该方法需要提前设置“默认”帧作为背景。在一些情况下,由于光照变化频繁,这种处理方法就显得很不灵活,因此,需要在系统中引入更智能的方法,即:背景分割器。

下一篇:《OpenCV3-Python之MOG2、KNN和GMG背景分割器》

注意:本站所有文章除特别说明外,均为原创,转载请务必以超链接方式并注明作者出处。 标签:opencv3,python,图像处理