作业记录 WEEK1

1. 人脸检测+关键点提取程序

安装dlib库

直接pip安装dlib库的时候遇到了error:
在这里插入图片描述
要先安装cmake:

pip install cmake

再pip安装就可以了。
在这里插入图片描述

模型文件

按照要求要先下载并解压shape_predictor_68_face_landmarks.dat模型文件,发现仓库里已经有了就直接复制了一份到代码文件目录下。

predictor = dlib.shape_predictor(r'./shape_predictor_68_face_landmarks.dat') # 同级目录下

图片文件person_not_exist.jpg获取

https://thispersondoesnotexist.com/
保存当前随机图片到代码文件目录下,修改文件后缀为.jpg。

–Code–

# coding:utf-8
import dlib
import numpy as np
from copy import deepcopy
import cv2
import os

#使用关键点模型需要提前下载此模型,并解压得到shape_predictor_68_face_landmarks.dat
#http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2

if __name__=="__main__":
    # 初始化dlib的人脸检测模型
    detector = dlib.get_frontal_face_detector()
    # 初始化关键点检测模型
    predictor = dlib.shape_predictor(r'./shape_predictor_68_face_landmarks.dat') # 同级目录下
    # 从这个网站上,拿一张不存在的人脸图片:https://thispersondoesnotexist.com 
    # 保存为person_not_exist.jpg
    if 1:
        # 读取图片
        frame_src = cv2.imread("person_not_exist.jpg")  # frame_src.shape: (1024,1024,3)
        # 将图片缩小为原来大小的1/3 ? 会降低清晰度 为什么要这么做呢
        x, y = frame_src.shape[0:2]
        frame = cv2.resize(frame_src, (int(y / 3), int(x / 3))) # frame.shape: (341,341,3)
        face_align = frame #?
        # [填空]使用检测模型对图片进行人脸检测
        dets = detector(frame,1) # The 1 in the second argument indicates that we should upsample the image 1 time. 
                                 # This will make everything bigger and allow us to detect more # faces. 
                                 # 这是官网给的解释。在图像上的采样次数。
                                 # returns a rectangle
        # 遍历检测结果
        for det in dets:
            #[填空] 对检测到的人脸提取人脸关键点
            shape = predictor(frame, det)
            # 在图片上绘制出检测模型得到的矩形框,框为绿色
            frame=cv2.rectangle(frame,(det.left(),det.top()),(det.right(),det.bottom()),(0,255,0),2)
            #[填空] 人脸对齐
            face_align = dlib.get_face_chip(frame, shape, size=150)
            # 将关键点绘制到人脸上,
            for i in range(68):
                cv2.putText(frame, str(i), (shape.part(i).x, shape.part(i).y), cv2.FONT_HERSHEY_DUPLEX, 0.3, (0, 255, 255), 1,cv2.LINE_AA)
                cv2.circle(frame, (shape.part(i).x, shape.part(i).y), 1, (0, 0, 255))
        # 显示图片,图片上有矩形框,关键点
        # 得到人脸检测和关键点的结果图片week1_detect_landmark.jpg
        cv2.imwrite("week1_detect_landmark.jpg",cv2.resize(frame,(y,x)))
        # 得到人脸对齐后的图片week1_align.jpg
        cv2.imwrite("week1_align.jpg",face_align)
        

运行结果

原图:在这里插入图片描述
人脸检测和关键点的结果图片:

在这里插入图片描述
人脸对齐后的图片:
在这里插入图片描述

2. 求y=x^2的最小值,用梯度下降的方法,不使用框架

import numpy as np
import matplotlib.pyplot as plt
plot_x = np.linspace(-10,10,500)   # 生成x
plot_y = (plot_x)**2 # 生成y,  y = x^2

###定义一个求二次函数导数的函数dJ
def dJ(x):
    return 2*x

###定义一个求函数值的函数J
def J(x):
    try:
        return x**2
    except:
        return float('inf')

x=9 # 随机选取一个起始点
lr=0.1 # 学习率
epsilon=1e-8 # 用来判断是否到达二次函数的最小值点的条件
history_x=[x] # 用来记录使用梯度下降法走过的点的X坐标
while True:
    gradient=dJ(x) # 梯度(导数)
    last_x=x
    x = x - lr * gradient
    history_x.append(x)
    if (abs(J(last_x)-J(x)) <epsilon): # 用来判断是否逼近最低点
        break

print(history_x) #打印到达最低点时x的值
plt.plot(plot_x,plot_y)     
plt.plot(np.array(history_x),J(np.array(history_x)),color='r',marker='*')   #绘制x的轨迹
plt.show()

运行结果:
在这里插入图片描述
可以看到最小值在 x = 0 x=0 x=0处收敛,此时 y m i n = 0 y_{min}=0 ymin=0

3. 用框架pytorch求出 l o s s loss loss的最小值,用梯度下降的方法

l o s s = ( 5 w 1 + 3 w 2 − 1 ) 2 + ( − 3 w 1 − 4 w 2 + 1 ) 2 loss=(5w_1+3w_2-1)^2+(-3w1-4w_2+1)^2 loss=(5w1+3w21)2+(3w14w2+1)2

import torch
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
import mpl_toolkits.mplot3d

figure=plt.figure()
figure.dpi=200

#ax = Axes3D(figure)
ax=figure.gca(projection="3d")
x1=np.linspace(-6,6,1000)
y1=np.linspace(-6,6,1000)
w1,w2 =np.meshgrid(x1,y1)
z=(5*w1 + 3*w2 - 1)**2+(-3*w1 -4*w2 + 1)**2
#ax.plot_surface(x,y,z,rstride=10,cstride=4,cmap=cm.YlGnBu_r)
ax.plot_surface(w1,w2,z,cmap="rainbow")
plt.show()

#梯度下降法寻找2D函数最优值函数
def f(x):
    return (5*x[0] + 3*x[1] - 1)**2+(-3*x[0] - 4*x[1] + 1)**2

x=torch.tensor([-4.,0.],requires_grad=True) #
optimizer=torch.optim.Adam([x],lr=1e-3)

for step in range(20000):
    pre=f(x)
    optimizer.zero_grad()
    pre.backward()
    optimizer.step()
    if step%2000==0:
        print(step,x.tolist,pre)

运行结果:
在这里插入图片描述

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值