0.说在前面1.pytorch安装及测试2.pytorch官网学习3.作者的话
继续cs231n的课程,我们学习到pytorch,这里给出安装过程及pytorch基本使用! 下面一起来学习吧!
输入
import torch
torch.__version__
输出
'0.4.1'
输入
torch.cuda.is_available()
输出
True
【安装包】
学习官网实例,需要安装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()
输出