|
下面是对人脸打码自动化方案的优化解答,包含进度条添加和漏打问题解决方案:
### 问题1:添加视频处理进度条
使用 `tqdm` 库实时显示处理进度,修改 `mosaic_faces` 函数:
- import cv2
- from mtcnn import MTCNN
- from tqdm import tqdm # 新增进度条库
- def mosaic_area(img, x, y, w, h, block_size=10):
- """修正版:正确替换原图像区域"""
- # 调整越界坐标
- y1, y2 = max(0, y), min(img.shape[0], y + h)
- x1, x2 = max(0, x), min(img.shape[1], x + w)
-
- # 截取有效区域
- roi = img[y1:y2, x1:x2]
- if roi.size == 0: # 空区域跳过
- return
-
- # 马赛克处理
- small = cv2.resize(roi, (8, 8), interpolation=cv2.INTER_LINEAR)
- mosaic = cv2.resize(small, (x2 - x1, y2 - y1), interpolation=cv2.INTER_NEAREST)
- img[y1:y2, x1:x2] = mosaic # 关键:替换原图区域
- def mosaic_faces(input_path, output_path, block_size=10, conf_threshold=0.8):
- detector = MTCNN()
- cap = cv2.VideoCapture(input_path)
-
- # 获取视频信息
- total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) # 总帧数
- fps = int(cap.get(cv2.CAP_PROP_FPS))
- width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
- height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
-
- # 初始化进度条
- pbar = tqdm(total=total_frames, desc="Processing Video")
-
- # 创建输出视频
- fourcc = cv2.VideoWriter_fourcc(*'mp4v')
- out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
- while True:
- ret, frame = cap.read()
- if not ret:
- break
-
- # 人脸检测与打码
- results = detector.detect_faces(frame)
- for res in results:
- if res['confidence'] < conf_threshold: # 置信度过滤
- continue
- x, y, w, h = res['box']
- mosaic_area(frame, x, y, w, h, block_size)
-
- out.write(frame)
- pbar.update(1) # 更新进度
-
- cap.release()
- out.release()
- pbar.close() # 关闭进度条
复制代码
### 问题2:解决马赛克"漏打"问题
通过以下两种方法提升检测准确率:
1. **调整置信度阈值**
- 降低 `conf_threshold` 值(默认0.8)检测更多人脸
- 示例:`mosaic_faces(..., conf_threshold=0.6)`
2. **多尺度检测增强**
初始化检测器时启用多尺度检测:
- detector = MTCNN(steps_threshold=[0.5, 0.6, 0.7]) # 降低P/R/O网络阈值
复制代码
### 使用说明
1. 安装依赖库:
pip install opencv-python tensorflow mtcnn tqdm
2. 执行主程序:
- if __name__ == "__main__":
- mosaic_faces("input.mp4", "output.mp4",
- block_size=15, # 马赛克块大小
- conf_threshold=0.7) # 人脸检测置信度
复制代码
> 注意事项:
> 1. 进度条长度 = 视频总帧数
> 2. 降低 `conf_threshold` 可能增加误检
> 3. 复杂场景建议结合 min_face_size 参数调整:
> detector = MTCNN(min_face_size=40)
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|