江大白《Opencv 基础及 AI 项目实战》课程——第二次作业

作业题目

  • 对于资料包中的兔耳朵帽子特效的图片处理代码学习。
  • 编写读取视频 video.mov,进行兔耳帽帽子特效的代码,实现对视频进行兔耳朵帽子特效。在作业中,将视频处理的其中一张效果图也截图附在作业中。
  • 将整个兔耳朵帽子特效的流程拆解,写出实现的步骤,和自己对于人脸特效的心得理
    解。
    在这里插入图片描述

1、视频图片截屏

在这里插入图片描述

2、流程拆解

  1. 人脸侦测
  2. 帽子处理
  3. 人脸图片处理
  4. 帽子和人脸组装

具体位置见代码注释

import cv2  # 图像处理的opencv库
import dlib  # 加载dlib算法模块
import argparse  # 加载解析模块


def hat_face(opt):
    detector = dlib.get_frontal_face_detector()
    cap = cv2.VideoCapture(opt.video_path)
    img_hat = cv2.imread(opt.hat_path)

    frame_id=0
    while True:
        ret, img = cap.read()
        
        # 人脸侦测
        faceRects = detector(img, 0)
        for box_info in faceRects:
            x0, y0, width_face, height_face = box_info.left(), box_info.top(), box_info.right() - box_info.left(), box_info.bottom() - box_info.top()
            
            # 帽子处理
            height_hat, width_hat = img_hat.shape[0], img_hat.shape[1]
            imgComposeSizeH = int(height_hat / width_hat * width_face)
            if imgComposeSizeH > (y0 - 20):
                imgComposeSizeH = (y0 - 20)
            imgComposeSize = cv2.resize(img_hat, (width_face, imgComposeSizeH), interpolation=cv2.INTER_NEAREST)
            top = (y0 - 20 - imgComposeSizeH)
            if top <= 0:
                top = 0
            height_hat_new, width_hat_new = imgComposeSize.shape[0], imgComposeSize.shape[1]
            small_img_hat = img[top:top + height_hat_new, x0:x0 + width_hat_new]
            small_img_hat_gray = cv2.cvtColor(imgComposeSize, cv2.COLOR_RGB2GRAY)
            ret, mask_hat = cv2.threshold(small_img_hat_gray, 10, 255, cv2.THRESH_BINARY)

            mask_hat_inv = cv2.bitwise_not(mask_hat)
            
            # 背景处理
            img1_bg = cv2.bitwise_and(small_img_hat, small_img_hat, mask=mask_hat_inv)
            img2_fg = cv2.bitwise_and(imgComposeSize, imgComposeSize, mask=mask_hat)
            dst = cv2.add(img1_bg, img2_fg)
            
            # 贴图
            img[top:top + height_hat_new, x0:x0 + width_hat_new] = dst

        img = cv2.resize(img, (500, 600))
        cv2.imshow("image", img)
        frame_id+=1
        if int(frame_id)%5!=0:continue
        cv2.waitKey(10)


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--video_path', default="video.mov", help='path of read video')
    parser.add_argument('--hat_path', default="maozi.png", help='path of hat image')

    opt = parser.parse_args()
    hat_face(opt)

3、心得体会

本次作业主要使用了opencv的一些图片处理的方法,对于我是一个复习的过程,有些知识点时间太久,有些忘记了,有一个这样作业的过程,能够更好的回顾

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值