OpenCv 从零开始第九天笔记 人脸轮廓替换

import cv2
import numpy as np
if __name__ == '__main__':
    img=cv2.imread('./123.jpg')
    head=cv2.imread('./dog.jpg')
    face_detector=cv2.CascadeClassifier('./haarcascade_frontalface_alt.xml')
    gray=cv2.cvtColor(img,code=cv2.COLOR_BGR2GRAY)
    headgray=cv2.cvtColor(head,cv2.COLOR_BGR2GRAY)
    thresshold,head_binary=cv2.threshold(headgray,100,255,cv2.THRESH_OTSU)
    contours,hierarchy=cv2.findContours(head_binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    areas=[]
    for contour in contours:
        areas.append(cv2.contourArea(contour))
    areas=np.asarray(areas)
    index=areas.argsort()#从小到大第二大的轮廓
    mask=np.zeros_like(headgray,dtype=np.uint8)
    cv2.drawContours(mask,contours,index[-2],(255,255,255),thickness=-1)
    faces=face_detector.detectMultiScale(gray)
    for x,y,w,h in faces:
        mask2=cv2.resize(mask,(w,h))
        head2=cv2.resize(head,(w,h))
        for i in range(h):
            for j in range(w):
                if (mask2[i,j] ==255).all():
                   img[i+y,j+x]= head2[i,j]

    cv2.imshow('face',img)
    print(thresshold)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

首先导入图片 ,分别为人脸图片和遮脸的图片

进而将两张图片转换为灰度图方便更好的使用,

thresshold,head_binary=cv2.threshold(headgray,100,255,cv2.THRESH_OTSU)

thresshold  域值:目标值根据区域值改变的结果

head_binary 非黑即白的图片,只有黑白之分

 THRESH_OTSU(大津算法)由日本学者于1979提出的一种对图像的二值化高效算法

contours,hierarchy=cv2.findContours(head_binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

contours 轮廓

hierarchy 层次结构

计算轮廓面积

areas=[]
for contour in contours:
    areas.append(cv2.contourArea(contour))

每计算出来的轮廓面积都放到areas中

绘画轮廓

areas=np.asarray(areas)
index=areas.argsort()#从小到大第二大的轮廓
mask=np.zeros_like(headgray,dtype=np.uint8)
cv2.drawContours(mask,contours,index[-2],(255,255,255),thickness=-1)

绘制人脸并替换

faces=face_detector.detectMultiScale(gray)
for x,y,w,h in faces:
    mask2=cv2.resize(mask,(w,h))
    head2=cv2.resize(head,(w,h))
    for i in range(h):
        for j in range(w):
            if (mask2[i,j] ==255).all():
               img[i+y,j+x]= head2[i,j]

最后得到的结果为:

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值