在video_path中更改自己视频的位置即可
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import cv2
video_path = 'D:/python/Practice/Leader.mp4' #存放视频的路径
commander = cv2.VideoCapture(video_path)
speed_factor = 2 # 视频播放速度的倍数
fig, ax = plt.subplots(figsize=(10, 6))
def update(frame):
for _ in range(speed_factor):
ret = commander.grab()
# 读取视频帧
ret, frame = commander.read()
if not ret:
return
# 将图像转换为灰度图像
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 应用 Canny 边缘检测
edges = cv2.Canny(gray_frame, 100, 200)
# 进行膨胀操作扩大边缘
kernel = np.ones((10,10), np.uint8) # 膨胀的核大小可以调整
edges_dilated = cv2.dilate(edges, kernel)
output_image = np.ones_like(frame) * 255 # 创建一个白色的图像,BGR格式
# 将边缘位置的像素设置为蓝色
output_image[edges_dilated != 0] = [0, 0, 255] # BGR格式,蓝色
# 清空当前轴并绘制新图像
ax.clear()
ax.imshow(output_image)
# 创建动画
ani = animation.FuncAnimation(fig, update, frames=20, interval=50)
plt.show()