国产片侵犯亲女视频播放_亚洲精品二区_在线免费国产视频_欧美精品一区二区三区在线_少妇久久久_在线观看av不卡

腳本之家,腳本語言編程技術(shù)及教程分享平臺!
分類導(dǎo)航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服務(wù)器之家 - 腳本之家 - Python - Python Pytorch深度學(xué)習(xí)之?dāng)?shù)據(jù)加載和處理

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

2022-02-19 14:06柚子味的羊 Python

今天小編就為大家分享一篇Pytorch 數(shù)據(jù)加載與數(shù)據(jù)預(yù)處理方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

一、下載安裝包

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)良好的圖片――處理的是一個面部姿態(tài)的數(shù)據(jù)集,也就是按照入戲方式標(biāo)注人臉

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

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

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

Python Pytorch深度學(xué)習(xí)之?dāng)?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]))

運行結(jié)果

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

 

四、編寫一個函數(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()

運行結(jié)果

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

 

五、數(shù)據(jù)集類

torch.utils.data.Dataset是表示數(shù)據(jù)集的抽象類,自定義數(shù)據(jù)類應(yīng)繼承Dataset并覆蓋__len__實現(xiàn)len(dataset)返還數(shù)據(jù)集的尺寸。__getitem__用來獲取一些索引數(shù)據(jù):

#%%數(shù)據(jù)集類――將數(shù)據(jù)集封裝成一個類
class FaceLandmarksDataset(Dataset):
  def __init__(self,csv_file,root_dir,transform=None):
      # csv_file(string):待注釋的csv文件的路徑
      # root_dir(string):包含所有圖像的目錄
      # transform(callabele,optional):一個樣本上的可用的可選變換
      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ù)據(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

運行結(jié)果

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

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

 

七、數(shù)據(jù)變換

由上圖可以發(fā)現(xiàn)每張圖像的尺寸大小是不同的。絕大多數(shù)神經(jīng)網(wǎng)路都嘉定圖像的尺寸相同。所以需要對圖像先進(jìn)行預(yù)處理。創(chuàng)建三個轉(zhuǎn)換:

Rescale:縮放圖片

RandomCrop:對圖片進(jìn)行隨機裁剪

ToTensor:把numpy格式圖片轉(zhuǎn)成torch格式圖片(交換坐標(biāo)軸)和上面同樣的方式,將其寫成一個類,這樣就不需要在每次調(diào)用的時候川第一此參數(shù),只需要實現(xiàn)__call__的方法,必要的時候使用__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

# 隨機裁剪樣本中的圖像
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ù)依舊表示想要裁剪后圖像的尺寸,如果是元組其而包含兩個元素直接復(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)用到實例中

Req: 把圖像的短邊調(diào)整為256,隨機裁剪(randomcrop)為224大小的正方形。即:組合一個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()

運行結(jié)果

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

 

九、迭代數(shù)據(jù)集

把這些整合起來以創(chuàng)建一個帶有組合轉(zhuǎn)換的數(shù)據(jù)集,總結(jié)一下沒每次這個數(shù)據(jù)集被采樣的時候:及時的從文件中讀取圖片,對讀取的圖片應(yīng)用轉(zhuǎn)換,由于其中一部是隨機的randomcrop,數(shù)據(jù)被增強了。可以使用循環(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    

運行結(jié)果

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

對所有數(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)注服務(wù)器之家的更多內(nèi)容!

原文鏈接:https://blog.csdn.net/qq_43368987/article/details/120970873

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 欧美日韩在线播放 | 亚洲国产一区二区三区在线播放 | 特黄网站 | 国产视频三区 | 精品国产乱码久久久久久丨区2区 | 中文字幕视频在线观看 | 91精品国产乱码久 | 午夜成年人 | 亚洲精品一区二区三区蜜桃下载 | 精品一二区 | 一级一片免费视频 | 色就是色网站 | 日韩精品视频一区二区三区 | 黄色成人在线 | 国产精品对白一区二区三区 | 91在线公开视频 | 精品在线一区二区三区 | 亚洲精品乱码久久久久久久久 | av福利在线观看 | 亚洲国产精品99久久久久久久久 | 日本淫片| 草比网站 | 毛片在线一区二区观看精品 | 欧美一区二区三区不卡 | av片在线观看 | 亚洲精品成人 | aaa综合国产 | av一区二区在线观看 | 丰满白嫩老熟女毛片 | 久久综合久色欧美综合狠狠 | 久久精品香蕉 | 国内自拍第一页 | 91视频久久 | 亚洲永久免费 | 五月激情综合网 | 操操操干干 | a级性生活片| 成人午夜啪啪好大 | 精品国产区一区二 | www.久久精品 | 亚洲欧洲日韩 |