搜索
Hi~登录注册
查看: 906|回复: 0

超详细注释之OpenCV实现视频实时人脸模糊和人脸马赛克

[复制链接]

0

主题

0

帖子

10

积分

新手上路

Rank: 1

积分
10
发表于 2021-9-14 16:22:33 | 显示全部楼层 |阅读模式
目录


  • 1. 效果图
  • 2. 原理

    • 2.1 什么是人脸模糊,如何将其用于人脸匿名化?
    • 2.2 执行人脸模糊/匿名化的步骤

  • 3. 源码

    • 3.1 图像人脸模糊源码
    • 3.2 实时视频流人脸模糊源码

  • 参考
这篇博客将介绍人脸检测,然后使用Python,OpenCV模糊它们来“匿名化”每张图像,以确保隐私得到保护,保证没有人脸可以被识别如何使用。
并介绍俩种模糊的方法:简单高斯模糊、像素模糊。
人脸模糊和匿名化的实际应用包括:
       
  • 公共/私人区域的隐私和身份保护   
  • 在线保护儿童(即在上传的照片中模糊未成年人的脸)   
  • 拍照新闻和新闻报道(如模糊未签订弃权书的人的脸)   
  • 数据集管理和分发(如在数据集中匿名化个人)

1. 效果图

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

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

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

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


2. 原理


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

人脸模糊是一种计算机视觉方法,用于对图像和视频中的人脸进行匿名化。
如上图中人的身份是不可辨认的,通常使用面部模糊来帮助保护图像中的人的身份。

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

人脸检测方法有很多,任选一种,进行图像中的人脸检测或者实时视频流中人脸的检测。人脸成功检测后可使用以下俩种方式进行模糊。
       
  • 使用高斯模糊对图像和视频流中的人脸进行匿名化   
  • 应用“像素模糊”效果来匿名化图像和视频中的人脸
应用OpenCV和计算机视觉进行人脸模糊包括四部分:
       
  • 进行人脸检测;(如Haar级联、HOG线性向量机、基于深度学习的检测);   
  • 提取ROI(Region Of Interests);   
  • 模糊/匿名化人脸;   
  • 将模糊的人脸存储回原始图像中(Numpy数组切片)。

3. 源码


3.1 图像人脸模糊源码
  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 argparseimport osimport cv2import imutilsimport numpy as npfrom pyimagesearch.face_blurring import anonymize_face_pixelatefrom 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]# 预处理惩罚图像,构建图像blobblob = 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")        # 提取面部ROI        face = 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"])        # 用模糊的匿名面部覆盖图像中的原始人脸ROI        image[startY:endY, startX:endX] = face# 原始图像和匿名图像并排表现output = np.hstack([orig, image])cv2.imshow("Origin VS " + str(args['method']), output)cv2.waitKey(0)
复制代码
3.2 实时视频流人脸模糊源码
  1. # USAGE# python blur_face_video.py --face face_detector# python blur_face_video.py --face face_detector --method pixelated# 导入必要的包import argparseimport osimport timeimport cv2import imutilsimport numpy as npfrom imutils.video import VideoStreamfrom pyimagesearch.face_blurring import anonymize_face_pixelatefrom 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)# 初始化视频流,预热传感器2sprint("[INFO] starting video stream...")vs = VideoStream(src=0).start()time.sleep(2.0)# 遍历视频流的每一帧while True:    # 从线程化的视频流获取一帧,保持宽高比的缩放宽度为400px    frame = 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")            # 提取面部ROI            face = 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覆盖图像中的原始人脸ROI            frame[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/
到此这篇关于超详细解释之OpenCV实现视频实时人脸模糊和人脸马赛克的文章就介绍到这了,更多相关OpenCV人脸马赛克内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望各人以后多多支持脚本之家!

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

游客
回复
您需要登录后才可以回帖 登录 | 点我注册

快速回复 返回顶部 返回列表