人妖在线一区,国产日韩欧美一区二区综合在线,国产啪精品视频网站免费,欧美内射深插日本少妇

新聞動(dòng)態(tài)

Python Pytorch深度學(xué)習(xí)之?dāng)?shù)據(jù)加載和處理

發(fā)布日期:2021-12-18 08:35 | 文章來(lái)源:CSDN

一、下載安裝包

packages:

  • scikit-image:用于圖像測(cè)IO和變換
  • pandas:方便進(jìn)行csv解析

二、下載數(shù)據(jù)集

數(shù)據(jù)集說(shuō)明:該數(shù)據(jù)集(我在這)是imagenet數(shù)據(jù)集標(biāo)注為face的圖片當(dāng)中在dlib面部檢測(cè)表現(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__用來(lái)獲取一些索引數(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)路都嘉定圖像的尺寸相同。所以需要對(duì)圖像先進(jìn)行預(yù)處理。創(chuàng)建三個(gè)轉(zhuǎn)換:

Rescale:縮放圖片

RandomCrop:對(duì)圖片進(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ù)制長(zhǎng)寬,如果是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ù)集

把這些整合起來(lái)以創(chuàng)建一個(gè)帶有組合轉(zhuǎn)換的數(shù)據(jù)集,總結(jié)一下沒每次這個(gè)數(shù)據(jù)集被采樣的時(shí)候:及時(shí)的從文件中讀取圖片,對(duì)讀取的圖片應(yīng)用轉(zhuǎn)換,由于其中一部是隨機(jī)的randomcrop,數(shù)據(jù)被增強(qiáng)了??梢允褂醚h(huán)對(duì)創(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é)果


對(duì)所有數(shù)據(jù)集簡(jiǎn)單使用for循環(huán)會(huì)犧牲很多功能——>麻煩,效率低?。「挠枚嗑€程并行進(jìn)行
torch.utils.data.DataLoader可以提供上述功能的迭代器。collate_fn參數(shù)可以決定如何對(duì)數(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é)

本篇文章就到這里了,希望能夠給你帶來(lái)幫助,也希望您能夠多多關(guān)注本站的更多內(nèi)容!

版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。

相關(guān)文章

實(shí)時(shí)開通

自選配置、實(shí)時(shí)開通

免備案

全球線路精選!

全天候客戶服務(wù)

7x24全年不間斷在線

專屬顧問(wèn)服務(wù)

1對(duì)1客戶咨詢顧問(wèn)

在線
客服

在線客服:7*24小時(shí)在線

客服
熱線

400-630-3752
7*24小時(shí)客服服務(wù)熱線

關(guān)注
微信

關(guān)注官方微信
頂部