这篇文章主要介绍了python+opencv怎么实现动态物体追踪,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
简单几行就可以实现对动态物体的追踪,足见opencv在图像处理上的强大。
python代码:
import cv2
import numpy as np
camera=cv2.VideoCapture(0)
firstframe=None
while True:
ret,frame = camera.read()
if not ret:
break
gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
gray=cv2.GaussianBlur(gray,(21,21),0)
if firstframe is None:
firstframe=gray
continue
frameDelta = cv2.absdiff(firstframe,gray)
thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.dilate(thresh, None, iterations=2)
# cnts= cv2.findContours(thresh.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
x,y,w,h=cv2.boundingRect(thresh)
frame=cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2)
cv2.imshow("frame", frame)
cv2.imshow("Thresh", thresh)
cv2.imshow("frame2", frameDelta)
key = cv2.waitKey(1)&0xFF
if key == ord("q"):
break
camera.release()
cv2.destroyAllWindows()
效果图
感谢你能够认真阅读完这篇文章,希望小编分享的“python+opencv怎么实现动态物体追踪”这篇文章对大家有帮助,同时也希望大家多多支持天达云,关注天达云行业资讯频道,更多相关知识等着你来学习!