目录
帧差法可以判断转场
直方图方法:
帧差法可以判断转场
import cv2
# 读取视频文件
cap = cv2.VideoCapture('your_video_file.mp4')
# 读取第一帧
ret, frame1 = cap.read()
prev_gray = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
while True:
# 读取下一帧
ret, frame2 = cap.read()
if not ret:
break
# 将当前帧转换为灰度图像
gray = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
# 计算当前帧与上一帧的差异
frame_diff = cv2.absdiff(prev_gray, gray)
# 设定一个阈值来判断变化
threshold = 30
ret, thresh = cv2.threshold(frame_diff, threshold, 255, cv2.THRESH_BINARY)
# 展示结果
cv2.imshow('Frame Difference', thresh)
# 更新上一帧
prev_gray = gray
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放资源
cap.release()
cv2.destroyAllWindows()
直方图方法:
import cv2
import numpy as np
# 读取视频文件
cap = cv2.VideoCapture('your_video_file.mp4')
# 读取第一帧
ret, frame1 = cap.read()
prev_hist = cv2.calcHist([frame1], [0, 1, 2], None, [256, 256, 256], [0, 256, 0, 256, 0, 256])
while True:
# 读取下一帧
ret, frame2 = cap.read()
if not ret:
break
# 计算当前帧的直方图
current_hist = cv2.calcHist([frame2], [0, 1, 2], None, [256, 256, 256], [0, 256, 0, 256, 0, 256])
# 比较当前帧和上一帧的直方图差异
hist_diff = cv2.compareHist(prev_hist, current_hist, cv2.HISTCMP_CORREL) # 可以尝试不同的比较方法
# 设定阈值判断转场
threshold = 0.8 # 设置阈值,根据实际情况调整
if hist_diff < threshold:
print("转场可能发生!")
# 更新上一帧的直方图
prev_hist = current_hist
# 释放资源
cap.release()
cv2.destroyAllWindows()