import cv2 # 初始化背景建模器 fgbg = cv2.createBackgroundSubtractorMOG2() # 读取视频文件 cap = cv2.VideoCapture('w5.mp4') while True: # 读取一帧图像 ret, frame = cap.read() if not ret: break # 对图像进行背景建模 fgmask = fgbg.apply(frame) # 缩放比例 scale_percent = 50 # 计算缩放后的新尺寸 width = int(frame.shape[1] * scale_percent / 100) height = int(frame.shape[0] * scale_percent / 100) dim = (width, height) # 缩放图像 frame = cv2.resize(frame, dim, interpolation=cv2.INTER_AREA) fgmask = cv2.resize(fgmask, dim, interpolation=cv2.INTER_AREA) # 对二值化结果进行形态学操作 kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel) # 寻找轮廓并绘制矩形框 contours, hierarchy = cv2.findContours(fgmask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for contour in contours: area = cv2.contourArea(contour) if area > 1500: # 去除过小的噪点 x, y, w, h = cv2.boundingRect(contour) cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2) # 显示结果 cv2.imshow('frame', frame) cv2.imshow('fgmask', fgmask) if cv2.waitKey(30) == ord('q'): break # 释放资源 cap.release() cv2.destroyAllWindows()能给这段程序加一个目标跟踪吗
时间: 2024-04-01 19:34:11 浏览: 193
TB62209FG 2相步进电机驱动芯片
可以给这段程序加上目标跟踪。一种简单的方法是使用OpenCV的cv2.Tracker类。在循环中,可以使用cv2.Tracker类来跟踪检测到的目标。以下是修改后的代码示例:
import cv2
# 初始化背景建模器
fgbg = cv2.createBackgroundSubtractorMOG2()
# 读取视频文件
cap = cv2.VideoCapture('w5.mp4')
# 初始化跟踪器
tracker = cv2.TrackerCSRT_create()
while True:
# 读取一帧图像
ret, frame = cap.read()
if not ret:
break
# 对图像进行背景建模
fgmask = fgbg.apply(frame)
# 缩放比例
scale_percent = 50
# 计算缩放后的新尺寸
width = int(frame.shape[1] * scale_percent / 100)
height = int(frame.shape[0] * scale_percent / 100)
dim = (width, height)
# 缩放图像
frame = cv2.resize(frame, dim, interpolation=cv2.INTER_AREA)
fgmask = cv2.resize(fgmask, dim, interpolation=cv2.INTER_AREA)
# 对二值化结果进行形态学操作
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)
# 寻找轮廓并绘制矩形框
contours, hierarchy = cv2.findContours(fgmask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
area = cv2.contourArea(contour)
if area > 1500: # 去除过小的噪点
x, y, w, h = cv2.boundingRect(contour)
# 初始化跟踪器
bbox = (x, y, w, h)
tracker.init(frame, bbox)
# 更新跟踪器
success, bbox = tracker.update(frame)
# 绘制矩形框
if success:
x, y, w, h = [int(i) for i in bbox]
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
# 显示结果
cv2.imshow('frame', frame)
cv2.imshow('fgmask', fgmask)
if cv2.waitKey(30) == ord('q'):
break
# 释放资源
cap.release()
cv2.destroyAllWindows()
阅读全文