使用Python,OpenCV实现图像和实时视频流中的人脸模糊和人脸马赛克

  • 1. 效果图
  • 2. 原理
    • 2.1 什么是人脸模糊,如何将其用于人脸匿名化?
    • 2.2 执行人脸模糊/匿名化的步骤
  • 3. 源码
    • 3.1 图像人脸模糊源码
    • 3.2 实时视频流人脸模糊源码
  • 参考

这篇博客将介绍人脸检测,然后使用Python,OpenCV模糊它们来“匿名化”每张图像,以确保隐私得到保护,保证没有人脸可以被识别如何使用。

并介绍俩种模糊的方法:简单高斯模糊、像素模糊

人脸模糊和匿名化的实际应用包括:

  • 公共/私人区域的隐私和身份保护
  • 在线保护儿童(即在上传的照片中模糊未成年人的脸)
  • 摄影新闻和新闻报道(如模糊未签署弃权书的人的脸)
  • 数据集管理和分发(如在数据集中匿名化个人)

1. 效果图

原始图 VS 简单高斯模糊效果图如下:

原始图 VS 像素模糊效果图如下:
在晚间新闻上看到的面部模糊正是像素模糊,主要是因为它比高斯模糊更“美观”;

多人的也可以哦:原始图 VS 简单高斯模糊效果图:

多人的也可以哦:原始图 VS 像素模糊效果图:

2. 原理

2.1 什么是人脸模糊,如何将其用于人脸匿名化?

人脸模糊是一种计算机视觉方法,用于对图像和视频中的人脸进行匿名化。

如上图中人的身份是不可辨认的,通常使用面部模糊来帮助保护图像中的人的身份。

2.2 执行人脸模糊/匿名化的步骤

人脸检测方法有很多,任选一种,进行图像中的人脸检测或者实时视频流中人脸的检测。人脸成功检测后可使用以下俩种方式进行模糊。

  • 使用高斯模糊对图像和视频流中的人脸进行匿名化
  • 应用“像素模糊”效果来匿名化图像和视频中的人脸

应用OpenCV和计算机视觉进行人脸模糊包括四部分:

  1. 进行人脸检测;(如Haar级联、HOG线性向量机、基于深度学习的检测);
  2. 提取ROI(Region Of Interests);
  3. 模糊/匿名化人脸;
  4. 将模糊的人脸存储回原始图像中(Numpy数组切片)。

3. 源码

3.1 图像人脸模糊源码

# USAGE
# python blur_face.py --image examples/we.jpg --face face_detector
# python blur_face.py --image examples/we.jpg --face face_detector --method pixelated# 使用OpenCV实现图像中的人脸模糊
# 导入必要的包
import argparse
import osimport cv2
import imutils
import numpy as np
from pyimagesearch.face_blurring import anonymize_face_pixelate
from pyimagesearch.face_blurring import anonymize_face_simple# 构建命令行参数及解析
# --image 输入人脸图像
# --face 人脸检测模型的目录
# --method 使用简单高斯模糊、像素模糊
# --blocks 面部分块数,默认20
# --confidence 面部检测置信度,过滤弱检测的值,默认50%
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,help="path to input image")
ap.add_argument("-f", "--face", required=True,help="path to face detector model directory")
ap.add_argument("-m", "--method", type=str, default="simple",choices=["simple", "pixelated"],help="face blurring/anonymizing method")
ap.add_argument("-b", "--blocks", type=int, default=20,help="# of blocks for the pixelated blurring method")
ap.add_argument("-c", "--confidence", type=float, default=0.5,help="minimum probability to filter weak detections")
args = vars(ap.parse_args())# 加载基于Caffe的人脸检测模型
# 从磁盘加载序列化的面部检测模型及标签文件
print("[INFO] loading face detector model...")
prototxtPath = os.path.sep.join([args["face"], "deploy.prototxt"])
weightsPath = os.path.sep.join([args["face"],"res10_300x300_ssd_iter_140000.caffemodel"])
net = cv2.dnn.readNet(prototxtPath, weightsPath)# 从此盘加载输入图像,获取图像维度
image = cv2.imread(args["image"])
image = imutils.resize(image, width=600)
orig = image.copy()
(h, w) = image.shape[:2]# 预处理图像,构建图像blob
blob = cv2.dnn.blobFromImage(image, 1.0, (300, 300),(104.0, 177.0, 123.0))# 传递blob到网络,并获取面部检测结果
print("[INFO] computing face detections...")
net.setInput(blob)
detections = net.forward()# 遍历人脸检测结果
for i in range(0, detections.shape[2]):# 提取检测的置信度,即可能性confidence = detections[0, 0, i, 2]# 过滤弱检测结果,确保均高于最小置信度if confidence > args["confidence"]:# 计算人脸的边界框(x,y)box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])(startX, startY, endX, endY) = box.astype("int")# 提取面部ROIface = image[startY:endY, startX:endX]# 检查是使用简单高斯模糊 还是 像素模糊方法if args["method"] == "simple":face = anonymize_face_simple(face, factor=3.0)# 否则应用像素匿名模糊方法else:face = anonymize_face_pixelate(face,blocks=args["blocks"])# 用模糊的匿名面部覆盖图像中的原始人脸ROIimage[startY:endY, startX:endX] = face# 原始图像和匿名图像并排显示
output = np.hstack([orig, image])
cv2.imshow("Origin VS " + str(args['method']), output)
cv2.waitKey(0)

3.2 实时视频流人脸模糊源码

# USAGE
# python blur_face_video.py --face face_detector
# python blur_face_video.py --face face_detector --method pixelated# 导入必要的包
import argparse
import os
import timeimport cv2
import imutils
import numpy as np
from imutils.video import VideoStream
from pyimagesearch.face_blurring import anonymize_face_pixelate
from pyimagesearch.face_blurring import anonymize_face_simple# 构建命令行参数及解析
# --face 人脸检测模型的目录
# --method 使用简单高斯模糊、像素模糊
# --blocks 面部分块数,默认20
# --confidence 面部检测置信度,过滤弱检测的值,默认50%
ap = argparse.ArgumentParser()
ap.add_argument("-f", "--face", required=True,help="path to face detector model directory")
ap.add_argument("-m", "--method", type=str, default="simple",choices=["simple", "pixelated"],help="face blurring/anonymizing method")
ap.add_argument("-b", "--blocks", type=int, default=20,help="# of blocks for the pixelated blurring method")
ap.add_argument("-c", "--confidence", type=float, default=0.5,help="minimum probability to filter weak detections")
args = vars(ap.parse_args())# 从磁盘加载训练好的人脸检测器Caffe模型
print("[INFO] loading face detector model...")
prototxtPath = os.path.sep.join([args["face"], "deploy.prototxt"])
weightsPath = os.path.sep.join([args["face"],"res10_300x300_ssd_iter_140000.caffemodel"])
net = cv2.dnn.readNet(prototxtPath, weightsPath)# 初始化视频流,预热传感器2s
print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()
time.sleep(2.0)# 遍历视频流的每一帧
while True:# 从线程化的视频流获取一帧,保持宽高比的缩放宽度为400pxframe = vs.read()frame = imutils.resize(frame, width=400)# 获取帧的维度,预处理帧(构建blob)(h, w) = frame.shape[:2]blob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300),(104.0, 177.0, 123.0))# 传递blob到网络并获取面部检测结果net.setInput(blob)detections = net.forward()# 遍历人脸检测结果for i in range(0, detections.shape[2]):# 提取检测的置信度,即可能性confidence = detections[0, 0, i, 2]# 过滤弱检测结果,确保均高于最小置信度if confidence > args["confidence"]:# 计算人脸的边界框(x,y)box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])(startX, startY, endX, endY) = box.astype("int")# 提取面部ROIface = frame[startY:endY, startX:endX]# 检查是使用简单高斯模糊 还是 像素模糊方法if args["method"] == "simple":face = anonymize_face_simple(face, factor=3.0)# 否则应用像素匿名模糊方法else:face = anonymize_face_pixelate(face,blocks=args["blocks"])# 用模糊的匿名面部ROI覆盖图像中的原始人脸ROIframe[startY:endY, startX:endX] = face# 展示输出帧cv2.imshow("Frame", frame)key = cv2.waitKey(1) & 0xFF# 按下‘q’键,退出循环if key == ord("q"):break# 做一些清理工作
# 关闭所有窗口,释放视频流指针
cv2.destroyAllWindows()
vs.stop()

参考

  • https://www.pyimagesearch.com/2020/04/06/blur-and-anonymize-faces-with-opencv-and-python/

使用Python,OpenCV实现图像和实时视频流中的人脸模糊和马赛克相关推荐

  1. python opencv 从Intel Realsense D435 视频流中读取并显示帧,按下空格将图像保存到指定文件夹,按下回车自动以一定时间间隔保存图像至指定文件夹

    参考文章1:opencv之读入一幅图像,显示图像以及如何保存一副图像,基础操作 参考文章2:python-OpenCV2中 cv2.VideoCapture(),read(),waitKey()的使用 ...

  2. Python+OpenCV:图像修复(Image Inpainting)

    Python+OpenCV:图像修复(Image Inpainting) 理论 Most of you will have some old degraded photos at your home ...

  3. Python+OpenCV:图像二进制鲁棒独立基本特征(BRIEF, Binary Robust Independent Elementary Features)

    Python+OpenCV:图像二进制鲁棒独立基本特征(BRIEF, Binary Robust Independent Elementary Features) 理论 We know SIFT us ...

  4. Python+OpenCV:图像快速角点检测算法(FAST Algorithm for Corner Detection)

    Python+OpenCV:图像快速角点检测算法(FAST Algorithm for Corner Detection) 理论 Feature Detection using FAST Select ...

  5. Python+OpenCV:图像Shi-Tomasi角点检测器

    Python+OpenCV:图像Shi-Tomasi角点检测器 理论 The scoring function in Harris Corner Detector was given by: Inst ...

  6. Python+OpenCV:图像Harris角点检测(Harris Corner Detection)

    Python+OpenCV:图像Harris角点检测(Harris Corner Detection) 理论 corners are regions in the image with large v ...

  7. Python+OpenCV:图像对比度受限自适应直方图均衡化(CLAHE, Contrast Limited Adaptive Histogram Equalization)

    Python+OpenCV:图像对比度受限自适应直方图均衡化(CLAHE, Contrast Limited Adaptive Histogram Equalization) ############ ...

  8. Python+OpenCV:图像轮廓

    Python+OpenCV:图像轮廓 轮廓是什么? 轮廓可以简单地解释为一条连接所有连续点(沿边界)的曲线,具有相同的颜色和强度. 轮廓线是形状分析.目标检测和识别的重要工具. 为了获得更好的精度,可 ...

  9. Python+OpenCV:图像金字塔

    Python+OpenCV:图像金字塔 理论 通常情况下,我们使用固定大小的图像.但在某些情况下,我们需要处理(相同的)不同分辨率的图像. 例如,当搜索图像中的某些东西时,比如脸,我们不确定该物体在图 ...

最新文章

  1. Linux系统文件安全与权限
  2. Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 't
  3. 【SA 认证课】来啦 这次陪你过双 11
  4. UDP穿透NAT原理解析
  5. 【网络爬虫入门02】HTTP客户端库Requests的基本原理与基础应用
  6. 在运行时在Spring Cloud Config中刷新属性配置
  7. python选择题题库百度文库_大学Python程序题题库
  8. MIT研发“读心机”:不开口也能对话,人生开挂全靠它
  9. 禅道项目管理工具环境搭建
  10. 高等数学学习笔记——第五十七讲——平面与直线的位置关系
  11. EPLAN p8 安装失败解决办法
  12. dcp9020cdn硒鼓!错误_打印机出现硒鼓错误怎么办?打印机显示硒鼓错误分析解决...
  13. 微信公众号自动回复及多客服功能实现
  14. Cisco Live 2016:CEO罗卓克谈英国脱欧、内部孵化以及向服务转型
  15. 欧拉回路专题 POJ - 1637网络流+混合图的欧拉回路
  16. 【转】iPhone通讯录AddressBook.framework和AddressBookUI.framework的应用
  17. 写给父亲的语音计算器(位图的加载,忽然领悟了资源编译器的加载c#,五)
  18. 企业级机械硬盘和消费级机械硬盘有什么区别?
  19. 如何得到每个区域的每个土地利用类型的面积
  20. aws mysql 多区_Amazon RDS 多可用区部署

热门文章

  1. 语义分割改进:通过视频传播和标签松弛
  2. 深度学习11个实用技巧
  3. git命令合并分支代码
  4. adb.exe: device offline
  5. Android 使用adb 抓取日志信息
  6. Daivik VM 和 JVM 的比较
  7. SharePoint2010 -- 管理配置文件同步
  8. 路由器虚拟服务器功能(广域网服务端口和局域网服务端口的映射关系)
  9. spring boot中的日志入门
  10. Linux磁盘空间满的处理方法