Files
COMP90044_a1/LBPTOP.py
2025-04-14 17:15:38 +10:00

61 lines
1.9 KiB
Python

import cv2
import numpy as np
from skimage.feature import local_binary_pattern
def extract_lbp_top(video_path, radius=2, n_points=8, method='uniform', block_size=10):
cap = cv2.VideoCapture(video_path)
frames = []
# 读取所有帧
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
frames.append(gray)
cap.release()
frames = np.array(frames)
T, H, W = frames.shape # 时间、空间维度
# 使用滑动窗口计算 XT, YT 平面
hist_xy = np.zeros((n_points + 2,))
hist_xt = np.zeros((n_points + 2,))
hist_yt = np.zeros((n_points + 2,))
# LBP on XY plane
for t in range(0, T, block_size):
if t >= T:
break
lbp = local_binary_pattern(frames[t], n_points, radius, method)
hist, _ = np.histogram(lbp.ravel(), bins=np.arange(0, n_points + 3), density=True)
hist_xy += hist
# LBP on XT plane
for y in range(0, H, block_size):
if y >= H:
break
xt_plane = frames[:, y, :]
lbp = local_binary_pattern(xt_plane, n_points, radius, method)
hist, _ = np.histogram(lbp.ravel(), bins=np.arange(0, n_points + 3), density=True)
hist_xt += hist
# LBP on YT plane
for x in range(0, W, block_size):
if x >= W:
break
yt_plane = frames[:, :, x]
lbp = local_binary_pattern(yt_plane, n_points, radius, method)
hist, _ = np.histogram(lbp.ravel(), bins=np.arange(0, n_points + 3), density=True)
hist_yt += hist
# 拼接三个平面的直方图作为最终特征向量
feature_vector = np.concatenate([hist_xy, hist_xt, hist_yt])
feature_vector /= np.linalg.norm(feature_vector) # 归一化
return feature_vector
video_path = r'D:\DESKTOP\2025\44\a1\dataset\org\1.mp4'
features = extract_lbp_top(video_path)
print(f"特征向量维度: {features.shape}")