视频内容中的品牌元素识别是广告检测的核心环节,通过Python可以搭建一套从视频解析到品牌特征匹配的完整流程,实现自动化广告识别。整个流程不需要依赖复杂的商业服务,仅靠开源库就能完成基础功能。

核心实现思路
整个识别流程可以分为四个核心步骤,每个步骤都有对应的Python库支撑,整体逻辑清晰且易于扩展。
- 视频帧提取:将视频按固定间隔拆解为静态图片,减少后续处理的计算量
- 品牌元素检测:从提取的帧中定位可能的品牌标识、文字、logo等元素
- 特征匹配:将检测到的元素与预设的品牌特征库做比对
- 结果判定:根据匹配结果和出现时长、频次等信息判定是否为广告内容
所需依赖库
实现上述功能需要安装以下Python库,可通过pip命令直接安装:
- OpenCV:用于视频读取、帧提取、图像基础处理
- pytesseract:用于提取帧中的文字内容,匹配品牌名称
- numpy:用于图像数据的数值计算
- hashlib:用于生成图像哈希,做logo相似度比对
视频帧提取源码实现
首先需要将视频按固定间隔提取帧,避免逐帧处理带来的性能浪费,通常每秒提取1-2帧即可满足基础识别需求。
import cv2
def extract_video_frames(video_path, save_interval=1):
"""
提取视频帧的函数
:param video_path: 视频文件路径
:param save_interval: 提取间隔,单位秒
:return: 提取的帧列表
"""
cap = cv2.VideoCapture(video_path)
fps = cap.get(cv2.CAP_PROP_FPS) # 获取视频帧率
frame_step = int(fps * save_interval) # 计算需要跳过的帧数
frame_list = []
frame_count = 0
while True:
ret, frame = cap.read()
if not ret:
break
# 按间隔提取帧
if frame_count % frame_step == 0:
frame_list.append(frame)
frame_count += 1
cap.release()
return frame_list
# 使用示例
if __name__ == "__main__":
video_path = "test_video.mp4"
frames = extract_video_frames(video_path, save_interval=1)
print(f"共提取到{len(frames)}帧")
品牌元素检测与匹配
提取到帧之后,需要分别检测其中的文字和logo元素,再和预设的品牌库做匹配。以下是文字检测和logo哈希比对的实现示例。
import pytesseract
import cv2
import hashlib
import numpy as np
# 预设的品牌库,包含品牌名称和对应的logo哈希值
BRAND_LIB = {
"示例品牌A": "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6",
"示例品牌B": "f6e5d4c3b2a1f0e9d8c7b6a5f4e3d2c1"
}
def get_image_hash(image):
"""生成图像的感知哈希值"""
# 缩放图像到固定尺寸
resized = cv2.resize(image, (8, 8), interpolation=cv2.INTER_AREA)
# 转为灰度图
gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)
# 计算平均值
avg = np.mean(gray)
# 生成哈希字符串
hash_str = ""
for i in range(8):
for j in range(8):
if gray[i, j] > avg:
hash_str += "1"
else:
hash_str += "0"
# 转为16进制字符串
return hex(int(hash_str, 2))[2:].zfill(16)
def detect_brand_in_frame(frame, brand_lib):
"""
检测单帧中的品牌元素
:param frame: 输入帧
:param brand_lib: 品牌库
:return: 匹配到的品牌名称列表
"""
matched_brands = []
# 1. 文字检测匹配品牌名称
text = pytesseract.image_to_string(frame, lang="chi_sim+eng")
for brand_name in brand_lib.keys():
if brand_name in text:
matched_brands.append(brand_name)
# 2. logo哈希匹配
frame_hash = get_image_hash(frame)
for brand_name, logo_hash in brand_lib.items():
# 计算哈希差异,差异小于5认为匹配
diff = sum(c1 != c2 for c1, c2 in zip(frame_hash, logo_hash))
if diff < 5 and brand_name not in matched_brands:
matched_brands.append(brand_name)
return matched_brands
# 使用示例
if __name__ == "__main__":
# 假设已经提取到一帧图像
test_frame = cv2.imread("test_frame.jpg")
matched = detect_brand_in_frame(test_frame, BRAND_LIB)
print(f"匹配到的品牌:{matched}")
广告判定逻辑
单帧匹配到品牌元素还不能直接判定为广告,需要结合品牌出现的连续时长和频次做综合判定,通常连续出现3秒以上或单视频中出现超过5次可判定为广告内容。
def judge_ad_content(frame_match_results, fps, min_duration=3, min_count=5):
"""
判定是否为广告内容
:param frame_match_results: 每帧的匹配结果列表,元素为匹配到的品牌列表
:param fps: 视频帧率
:param min_duration: 最小连续出现时长,单位秒
:param min_count: 最小出现次数
:return: 是否为广告,对应的品牌
"""
# 统计每个品牌的出现情况
brand_continuous = {} # 记录品牌连续出现的帧数
brand_total_count = {} # 记录品牌总出现次数
for frame_brands in frame_match_results:
# 先处理上一帧的连续计数
for brand in list(brand_continuous.keys()):
if brand not in frame_brands:
del brand_continuous[brand]
# 处理当前帧的品牌
for brand in frame_brands:
brand_total_count[brand] = brand_total_count.get(brand, 0) + 1
brand_continuous[brand] = brand_continuous.get(brand, 0) + 1
# 判定逻辑
for brand, continuous_frames in brand_continuous.items():
continuous_duration = continuous_frames / fps
total_count = brand_total_count[brand]
if continuous_duration >= min_duration or total_count >= min_count:
return True, brand
return False, None
# 使用示例
if __name__ == "__main__":
# 模拟10帧的匹配结果,假设品牌A连续出现5帧,帧率为25
frame_results = [[], [], ["示例品牌A"], ["示例品牌A"], ["示例品牌A"], ["示例品牌A"], ["示例品牌A"], [], [], []]
is_ad, brand = judge_ad_content(frame_results, fps=25, min_duration=3)
print(f"是否为广告:{is_ad},品牌:{brand}")
优化方向
上述是基础实现方案,实际落地时可以根据需求做进一步优化:
- 增加目标检测模型,比如用YOLO训练品牌logo检测模型,提升logo定位准确率
- 优化品牌库管理,支持动态添加、更新品牌特征,不需要修改核心代码
- 增加音频识别逻辑,匹配广告中的品牌音频特征,提升识别覆盖率
- 对视频做分段处理,支持大文件的并行识别,提升处理效率