美文网首页
给我一顶圣诞帽

给我一顶圣诞帽

作者: sugarAI是天字第一号衬衫 | 来源:发表于2017-12-28 08:02 被阅读0次

    原文来源:https://zhuanlan.zhihu.com/p/32283641
    Github上的python代码及素材库: https://github.com/LiuXiaolong19920720/Add-Christmas-Hat

    偶然在知乎上看到有人用python代码实现给头像加上圣诞帽, 遂跟着教程尝试之。

    实验环境及文章中用到的库:

    OpenCV

    是一个跨平台计算机视觉库,OpenCV可用于开发实时的图像处理、计算机视觉以及模式识别程序。OpenCV有两个Python接口,老版本的cv模块使用OpenCV内置的数据类型,新版本的cv2模块使用NumPy数组。

    Dlib

    Dlib是一个机器学习的C++库,包含了许多机器学习常用的算法。作者使用它是由于dlib的人脸识别能力强于OpenCV中的人脸识别(并包含人脸的关键点检验)

    环境

    我依然使用的是windows系统下的Anaconda并用jupyter notebook完成编译

    准备工作:

    下载openCV库
    在windows powershell中键入 conda install -c menpo cv2
    下载dlib库
    在windows powershell中键入 conda install -c conda-forge dlib 或者conda install -c menpo dlib
    实验中用到的素材可在作者的github上下载:https://github.com/LiuXiaolong19920720/Add-Christmas-Hat

    (1)圣诞帽素材


    hat.jpg
    hat2.png

    注:关于这两图的差别在于用hat.png的shape是三维(R,G,B)层而hat2.png的shape是四维(R,G,B,α)层,这一点可以通过img.shape查询:

    hat_img = cv2.imread("hat.png")
    print hat_img.shape
    hat2_img = cv2.imread("hat2.png",-1)
    print hat2_img.shape
    

    输出结果如下:
    (579, 717, 3)
    (702, 880, 4)
    前两个数字代表图像的大小,由第三个数字可得hat2.png是4维, cv2.imread中的第二个参数-1是提取alpha通道, 至于hat.png存在的意义...我还在问作者...
    在这里顺便介绍一下shape提取的四个维度是什么吧...
    前三个维度R,G,B分别是红色通道,绿色通道,蓝色通道, 你可以将之理解为一副图我们分别在三个通道上着色,覆盖混合在一起生成的新的颜色就是我们最后在图像上看到的颜色。α(阿尔法)通道(也就是我们提取的-1,最后一个通道)指的是特别的通道,意思是“非彩色”通道,主要是用来保存选区和编辑选区,用来描述图片的透明与半透明度。值得一提的是, png图像具有α通道而jpg图像没有。
    (2) 头像素材
    这个就自己随便在网上选啦, 最好选择含人物正脸的图像(用到的是dlib中的get_frontal_face_detector), 由于我们用的dlib的数据库的学习对象大都是人物头像, 好像萌宠与二次元人物的人脸是无法识别的目前。 我充满恶意的用了这一张:


    test.jpg

    (3)人脸识别数据库
    依然见作者的github, 文件名是shape_predictor_5_face_landmarks.dat

    代码部分

    首先依然是导入我们需要的库:刚刚下载好的dlib,cv2还有用作计算的NumPy.

    import dlib
    import cv2
    import numpy as np
    

    把加帽子写成一个完整的函数啦
    这一段实现的分别是:
    <1>将帽子素材图分离为r,g,b,α通道
    <2> 将帽子图的r,g,b三通道合成在一起
    <3>将α通道图层保存,将帽子图的

    def add_hat(img,hat_img):
        # 分离rgba通道,合成rgb三通道帽子图,a通道后面做mask用
        r,g,b,a = cv2.split(hat_img) 
        rgb_hat = cv2.merge((r,g,b))
    
        cv2.imwrite("hat_alpha.jpg",a)
    

    保存成功的alpha通道帽子图如下:


    hat_alpha.jpg

    下面这一段是用我们刚刚提到的从作者github上下载的人脸识别数据库进行人脸识别以及正脸检测

        # dlib人脸关键点检测器
        predictor_path = "shape_predictor_5_face_landmarks.dat"
        predictor = dlib.shape_predictor(predictor_path)  
    
        # dlib正脸检测器
        detector = dlib.get_frontal_face_detector()
    
        # 正脸检测
        dets = detector(img, 1)
    

    检测到人脸后的处理过程,细节解释见代码中#后的注释部分,#中的非文字说明部分为原作者的测试代码。

        # 如果检测到人脸
        # x,y,w,h 分别为检测到的正脸裁剪出的正方形图块对应的坐标点
        # 正脸正方形图块左上角坐标为(x,y), 右下角坐标为(x+w, y+h)
        if len(dets)>0:  
            for d in dets:
                x,y,w,h = d.left(),d.top(), d.right()-d.left(), d.bottom()-d.top()
    
    
                # 关键点检测,5个关键点
                shape = predictor(img, d)
                # for point in shape.parts():
                #     cv2.circle(img,(point.x,point.y),3,color=(0,255,0))
    
                # cv2.imshow("image",img)
                # cv2.waitKey()  
    
                # 选取左右眼眼角的点
                point1 = shape.part(0)
                point2 = shape.part(2)
    
                # 求两点中心
                eyes_center = ((point1.x+point2.x)//2,(point1.y+point2.y)//2)
    
                # cv2.circle(img,eyes_center,3,color=(0,255,0))  
                # cv2.imshow("image",img)
                # cv2.waitKey()
    
                #  根据人脸大小调整帽子大小
                factor = 1.5
                resized_hat_h = int(round(rgb_hat.shape[0]*w/rgb_hat.shape[1]*factor))
                resized_hat_w = int(round(rgb_hat.shape[1]*w/rgb_hat.shape[1]*factor))
    
                if resized_hat_h > y:
                    resized_hat_h = y-1
                     # 根据人脸大小调整帽子大小
                resized_hat = cv2.resize(rgb_hat,(resized_hat_w,resized_hat_h))
    
                # 用alpha通道作为mask
                mask = cv2.resize(a,(resized_hat_w,resized_hat_h))
                mask_inv =  cv2.bitwise_not(mask)
    
                # 帽子相对与人脸框上线的偏移量
                dh = 0
                dw = 0
                # 原图ROI
                # bg_roi = img[y+dh-resized_hat_h:y+dh, x+dw:x+dw+resized_hat_w]
                bg_roi = img[y+dh-resized_hat_h:y+dh,(eyes_center[0]-resized_hat_w//3):(eyes_center[0]+resized_hat_w//3*2)]
    
                # 原图ROI中提取放帽子的区域
                bg_roi = bg_roi.astype(float)
                mask_inv = cv2.merge((mask_inv,mask_inv,mask_inv))
                alpha = mask_inv.astype(float)/255
    
                # 相乘之前保证两者大小一致(可能会由于四舍五入原因不一致)
                alpha = cv2.resize(alpha,(bg_roi.shape[1],bg_roi.shape[0]))
                # print("alpha size: ",alpha.shape)
                # print("bg_roi size: ",bg_roi.shape)
                bg = cv2.multiply(alpha, bg_roi)
                bg = bg.astype('uint8')
    
                cv2.imwrite("bg.jpg",bg)
                # cv2.imshow("image",img)
                # cv2.waitKey()
    
                # 提取帽子区域
                hat = cv2.bitwise_and(resized_hat,resized_hat,mask = mask)
                cv2.imwrite("hat.jpg",hat)
                
                # cv2.imshow("hat",hat)  
                # cv2.imshow("bg",bg)
    
                # print("bg size: ",bg.shape)
                # print("hat size: ",hat.shape)
    
                # 相加之前保证两者大小一致(可能会由于四舍五入原因不一致)
                hat = cv2.resize(hat,(bg_roi.shape[1],bg_roi.shape[0]))
                # 两个ROI区域相加
                add_hat = cv2.add(bg,hat)
                # cv2.imshow("add_hat",add_hat) 
    
                # 把添加好帽子的区域放回原图
                img[y+dh-resized_hat_h:y+dh,(eyes_center[0]-resized_hat_w//3) (eyes_center[0]+resized_hat_w//3*2)] = add_hat
    
                # 展示效果
                # cv2.imshow("img",img )  
                # cv2.waitKey(0)  
    
                return img
    

    调用函数

    # 读取帽子图,第二个参数-1表示读取为rgba通道,否则为rgb通道
    hat_img = cv2.imread("hat2.png",-1)
    
    # 读取头像图
    img = cv2.imread("test.jpg")
    output = add_hat(img,hat_img)
    
    # 展示效果
    cv2.imshow("output",output )  
    cv2.waitKey(0)  
    cv2.imwrite("output.jpg",output)
    

    最后我得到的头像效果还可以,如下:


    output.jpg

    圣诞是来不及了,大家新年快乐!

    以上

    相关文章

      网友评论

          本文标题:给我一顶圣诞帽

          本文链接:https://www.haomeiwen.com/subject/enqmgxtx.html