Pytorch安裝及學習人臉特徵點識別

  • 2019 年 10 月 5 日
  • 筆記

Pytorch學習

0.說在前面1.pytorch安裝及測試2.pytorch官網學習3.作者的話

0.說在前面

繼續cs231n的課程,我們學習到pytorch,這裡給出安裝過程及pytorch基本使用! 下面一起來學習吧!

1.pytorch安裝及測試

  • 檢查cuda版本
  • Pytorch官網下載
  • 輸入官網下載命令
  • 測試

輸入

import torch  torch.__version__  

輸出

'0.4.1'  
  • 測試cuda可用性

輸入

torch.cuda.is_available()  

輸出

True  

2.pytorch官網學習

安裝包

學習官網實例,需要安裝scikit-image包,安裝方式如下:

pip install -U scikit-image  

導包

from __future__ import print_function, division  import os  import torch  import pandas as pd  from skimage import io, transform  import numpy as np  import matplotlib.pyplot as plt  from torch.utils.data import Dataset, DataLoader  from torchvision import transforms, utils  # 忽略警告  import warnings  warnings.filterwarnings("ignore")  plt.ion()   # 交互模式  

數據集

數據集下載地址: https://download.pytorch.org/tutorial/faces.zip

載入數據

landmarks_frame = pd.read_csv('faces/face_landmarks.csv')  

查看數據格式

查看前5行數據:

landmarks_frame.head(5)  

5行137列,去掉第一列影像名字,後面總共136列,每一個點包含x與y坐標,表示總共有68個特徵點!

繪製影像特徵點

提取影像名字

n = 4  img_name = landmarks_frame.iloc[n, 0]  img_name  

輸出

'1198_0_861.jpg'  

將影像的特徵點放到一個數組中

# 並不是矩陣化,而是一個數組中!  landmarks = landmarks_frame.iloc[n, 1:].as_matrix()  landmarks  

輸出

array([138, 392, 141, 427, 145, 464, 152, 501, 166, 536, 186, 567, 214,         594, 249, 614, 290, 616, 329, 608, 363, 589, 390, 562, 411, 529,         ...         294, 516, 279, 518, 265, 516], dtype=object)  

將每個點坐標表示一行數據

# 一行表示點的x與y坐標,形成(n,2)數組!  # -1 表示模糊匹配  landmarks = landmarks.astype('float').reshape(-1, 2)  # 列印輸出前5行數據  landmarks[:5,:]  

輸出

array([[138., 392.],         [141., 427.],         [145., 464.],         [152., 501.],         [166., 536.]])  

定義特徵點繪製方法

def show_landmarks(image, landmarks):      """Show image with landmarks"""      plt.imshow(image)      plt.scatter(landmarks[:, 0], landmarks[:, 1], s=10, marker='.', c='r')      plt.pause(0.001)  # pause a bit so that plots are updated  

特徵點繪製

plt.figure()  show_landmarks(io.imread(os.path.join('faces/', img_name)),landmarks)  plt.show()  

輸出