Python Pytorch深度學(xué)習(xí)之?dāng)?shù)據(jù)加載和處理
一、下載安裝包
packages:
scikit-image:用于圖像測IO和變換pandas:方便進(jìn)行csv解析
二、下載數(shù)據(jù)集
數(shù)據(jù)集說明:該數(shù)據(jù)集(我在這)是imagenet數(shù)據(jù)集標(biāo)注為face的圖片當(dāng)中在dlib面部檢測表現(xiàn)良好的圖片——處理的是一個(gè)面部姿態(tài)的數(shù)據(jù)集,也就是按照入戲方式標(biāo)注人臉

數(shù)據(jù)集展示


三、讀取數(shù)據(jù)集
#%%讀取數(shù)據(jù)集
landmarks_frame=pd.read_csv('D:/Python/Pytorch/data/faces/face_landmarks.csv')
n=65
img_name=landmarks_frame.iloc[n,0]
landmarks=landmarks_frame.iloc[n,1:].values
landmarks=landmarks.astype('float').reshape(-1,2)
print('Image name :{}'.format(img_name))
print('Landmarks shape :{}'.format(landmarks.shape))
print('First 4 Landmarks:{}'.format(landmarks[:4]))
運(yùn)行結(jié)果

四、編寫一個(gè)函數(shù)看看圖像和landmark
#%%編寫顯示人臉函數(shù)
def show_landmarks(image,landmarks):
plt.imshow(image)
plt.scatter(landmarks[:,0],landmarks[:,1],s=10,marker=".",c='r')
plt.pause(0.001)
plt.figure()
show_landmarks(io.imread(os.path.join('D:/Python/Pytorch/data/faces/',img_name)),landmarks)
plt.show()
運(yùn)行結(jié)果

五、數(shù)據(jù)集類
torch.utils.data.Dataset是表示數(shù)據(jù)集的抽象類,自定義數(shù)據(jù)類應(yīng)繼承Dataset并覆蓋__len__實(shí)現(xiàn)len(dataset)返還數(shù)據(jù)集的尺寸。__getitem__用來獲取一些索引數(shù)據(jù):
#%%數(shù)據(jù)集類——將數(shù)據(jù)集封裝成一個(gè)類
class FaceLandmarksDataset(Dataset):
def __init__(self,csv_file,root_dir,transform=None):
# csv_file(string):待注釋的csv文件的路徑
# root_dir(string):包含所有圖像的目錄
# transform(callabele,optional):一個(gè)樣本上的可用的可選變換
self.landmarks_frame=pd.read_csv(csv_file)
self.root_dir=root_dir
self.transform=transform
def __len__(self):
return len(self.landmarks_frame)
def __getitem__(self, idx):
img_name=os.path.join(self.root_dir,self.landmarks_frame.iloc[idx,0])
image=io.imread(img_name)
landmarks=self.landmarks_frame.iloc[idx,1:]
landmarks=np.array([landmarks])
landmarks=landmarks.astype('float').reshape(-1,2)
sample={'image':image,'landmarks':landmarks}
if self.transform:
sample=self.transform(sample)
return sample
六、數(shù)據(jù)可視化
#%%數(shù)據(jù)可視化
# 將上面定義的類進(jìn)行實(shí)例化并便利整個(gè)數(shù)據(jù)集
face_dataset=FaceLandmarksDataset(csv_file='D:/Python/Pytorch/data/faces/face_landmarks.csv',
root_dir='D:/Python/Pytorch/data/faces/')
fig=plt.figure()
for i in range(len(face_dataset)) :
sample=face_dataset[i]
print(i,sample['image'].shape,sample['landmarks'].shape)
ax=plt.subplot(1,4,i+1)
plt.tight_layout()
ax.set_title('Sample #{}'.format(i))
ax.axis('off')
show_landmarks(**sample)
if i==3:
plt.show()
break
運(yùn)行結(jié)果


七、數(shù)據(jù)變換
由上圖可以發(fā)現(xiàn)每張圖像的尺寸大小是不同的。絕大多數(shù)神經(jīng)網(wǎng)路都嘉定圖像的尺寸相同。所以需要對圖像先進(jìn)行預(yù)處理。創(chuàng)建三個(gè)轉(zhuǎn)換:
Rescale:縮放圖片
RandomCrop:對圖片進(jìn)行隨機(jī)裁剪
ToTensor:把numpy格式圖片轉(zhuǎn)成torch格式圖片(交換坐標(biāo)軸)和上面同樣的方式,將其寫成一個(gè)類,這樣就不需要在每次調(diào)用的時(shí)候川第一此參數(shù),只需要實(shí)現(xiàn)__call__的方法,必要的時(shí)候使用__init__方法
1、Function_Rescale
# 將樣本中的圖像重新縮放到給定的大小
class Rescale(object):
def __init__(self,output_size):
assert isinstance(output_size,(int,tuple))
self.output_size=output_size
#output_size 為int或tuple,如果是元組輸出與output_size匹配,
#如果是int,匹配較小的圖像邊緣到output_size保持縱橫比相同
def __call__(self,sample):
image,landmarks=sample['image'],sample['landmarks']
h,w=image.shape[:2]
if isinstance(self.output_size, int):#輸入?yún)?shù)是int
if h>w:
new_h,new_w=self.output_size*h/w,self.output_size
else:
new_h,new_w=self.output_size,self.output_size*w/h
else:#輸入?yún)?shù)是元組
new_h,new_w=self.output_size
new_h,new_w=int(new_h),int(new_w)
img=transform.resize(image, (new_h,new_w))
landmarks=landmarks*[new_w/w,new_h/h]
return {'image':img,'landmarks':landmarks}
2、Function_RandomCrop
# 隨機(jī)裁剪樣本中的圖像
class RandomCrop(object):
def __init__(self,output_size):
assert isinstance(output_size, (int,tuple))
if isinstance(output_size, int):
self.output_size=(output_size,output_size)
else:
assert len(output_size)==2
self.output_size=output_size
# 輸入?yún)?shù)依舊表示想要裁剪后圖像的尺寸,如果是元組其而包含兩個(gè)元素直接復(fù)制長寬,如果是int,則裁剪為方形
def __call__(self,sample):
image,landmarks=sample['image'],sample['landmarks']
h,w=image.shape[:2]
new_h,new_w=self.output_size
#確定圖片裁剪位置
top=np.random.randint(0,h-new_h)
left=np.random.randint(0,w-new_w)
image=image[top:top+new_h,left:left+new_w]
landmarks=landmarks-[left,top]
return {'image':image,'landmarks':landmarks}
3、Function_ToTensor
#%%
# 將樣本中的npdarray轉(zhuǎn)換為Tensor
class ToTensor(object):
def __call__(self,sample):
image,landmarks=sample['image'],sample['landmarks']
image=image.transpose((2,0,1))#交換顏色軸
#numpy的圖片是:Height*Width*Color
#torch的圖片是:Color*Height*Width
return {'image':torch.from_numpy(image),
'landmarks':torch.from_numpy(landmarks)}
八、組合轉(zhuǎn)換
將上面編寫的類應(yīng)用到實(shí)例中
Req: 把圖像的短邊調(diào)整為256,隨機(jī)裁剪(randomcrop)為224大小的正方形。即:組合一個(gè)Rescale和RandomCrop的變換。
#%%
scale=Rescale(256)
crop=RandomCrop(128)
composed=transforms.Compose([Rescale(256),RandomCrop(224)])
# 在樣本上應(yīng)用上述變換
fig=plt.figure()
sample=face_dataset[65]
for i,tsfrm in enumerate([scale,crop,composed]):
transformed_sample=tsfrm(sample)
ax=plt.subplot(1,3,i+1)
plt.tight_layout()
ax.set_title(type(tsfrm).__name__)
show_landmarks(**transformed_sample)
plt.show()
運(yùn)行結(jié)果

九、迭代數(shù)據(jù)集
把這些整合起來以創(chuàng)建一個(gè)帶有組合轉(zhuǎn)換的數(shù)據(jù)集,總結(jié)一下沒每次這個(gè)數(shù)據(jù)集被采樣的時(shí)候:及時(shí)的從文件中讀取圖片,對讀取的圖片應(yīng)用轉(zhuǎn)換,由于其中一部是隨機(jī)的randomcrop,數(shù)據(jù)被增強(qiáng)了??梢允褂醚h(huán)對創(chuàng)建的數(shù)據(jù)集執(zhí)行同樣的操作
transformed_dataset=FaceLandmarksDataset(csv_file='D:/Python/Pytorch/data/faces/face_landmarks.csv',
root_dir='D:/Python/Pytorch/data/faces/',
transform=transforms.Compose([
Rescale(256),
RandomCrop(224),
ToTensor()
]))
for i in range(len(transformed_dataset)):
sample=transformed_dataset[i]
print(i,sample['image'].size(),sample['landmarks'].size())
if i==3:
break
運(yùn)行結(jié)果

對所有數(shù)據(jù)集簡單使用for循環(huán)會犧牲很多功能——>麻煩,效率低?。「挠枚嗑€程并行進(jìn)行
torch.utils.data.DataLoader可以提供上述功能的迭代器。collate_fn參數(shù)可以決定如何對數(shù)據(jù)進(jìn)行批處理,絕大多數(shù)情況下默認(rèn)值就OK
transformed_dataset=FaceLandmarksDataset(csv_file='D:/Python/Pytorch/data/faces/face_landmarks.csv',
root_dir='D:/Python/Pytorch/data/faces/',
transform=transforms.Compose([
Rescale(256),
RandomCrop(224),
ToTensor()
]))
for i in range(len(transformed_dataset)):
sample=transformed_dataset[i]
print(i,sample['image'].size(),sample['landmarks'].size())
if i==3:
break
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
Django框架獲取form表單數(shù)據(jù)方式總結(jié)
這篇文章主要介紹了Django框架獲取form表單數(shù)據(jù)方式總結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04
Python+wxPython實(shí)現(xiàn)合并多個(gè)文本文件
在?Python?編程中,我們經(jīng)常需有時(shí)候,我們可能需要將多個(gè)文本文件合并成一個(gè)文件,要處理文本文件,本文就來介紹下如何使用?wxPython?模塊編寫一個(gè)簡單的程序,能夠讓用戶選擇多個(gè)文本文件,感興趣的可以了解下2023-08-08
Python?中如何使用requests模塊發(fā)布表單數(shù)據(jù)
requests 庫是 Python 的主要方面之一,用于創(chuàng)建對已定義 URL 的 HTTP 請求,本篇文章介紹了 Python requests 模塊,并說明了我們?nèi)绾问褂迷撃K在 Python 中發(fā)布表單數(shù)據(jù),感興趣的朋友跟隨小編一起看看吧2023-06-06
python讀寫Excel表格的實(shí)例代碼(簡單實(shí)用)
這篇文章主要介紹了python讀寫Excel表格的方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-12-12
pyecharts中from pyecharts import options
本文主要介紹了pyecharts中from pyecharts import options as opts報(bào)錯(cuò)問題以及解決辦法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07
關(guān)于python簡單的爬蟲操作(requests和etree)
這篇文章主要介紹了關(guān)于python簡單的爬蟲操作(requests和etree),文中提供了實(shí)現(xiàn)代碼,需要的朋友可以參考下2023-04-04
pandas實(shí)現(xiàn)DataFrame顯示最大行列,不省略顯示實(shí)例
今天小編就為大家分享一篇pandas實(shí)現(xiàn)DataFrame顯示最大行列,不省略顯示實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
詳解Pytorch 使用Pytorch擬合多項(xiàng)式(多項(xiàng)式回歸)
這篇文章主要介紹了詳解Pytorch 使用Pytorch擬合多項(xiàng)式(多項(xiàng)式回歸),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-05-05

