2017-12-01 20 views
0

깊은 학습 튜토리얼 웹 사이트에서이 코드는 다음과 같은 이미지를 읽는 것으로 나타났습니다.python : 깊은 학습을위한 RGB 이미지 읽기

cv2.resize(cv2.imread(folder + name, 1), (100, 200)).reshape(3, 100, 200) 

이 코드는 이미지 모양을 (100,200,3)에서 (3,100,200)으로 바꿉니다. 함수가 행렬의 모양을 어떻게 바꿔 놓았는지 알아 보았습니다. 이상한 결과를 얻었습니다.
아래와 같이 2x4 RGB 이미지 (d)를 가정하십시오.

d = array([[[ 1, 2, 3],[ 4, 5, 6],[ 7, 8, 9], [10, 11, 12]],[[13, 14, 15],[16, 17, 18], [19, 20, 21],[22, 23, 24]]]) 
d.shape: (2, 4, 3) 

바꿀 적용한 후에는

d.reshape(3,2,4) 
array([[[ 1, 2, 3, 4], 
     [ 5, 6, 7, 8]], 
     [[ 9, 10, 11, 12], 
     [ 13, 14, 15, 16]], 
     [[ 17, 18, 19, 20], 
     [ 21, 22, 23, 24]]]) 

을 보여줍니다하지만 우리는 아래와 같은 이미지를 표현하기 원하기 때문에 나는이 적절한 표현이라고 생각하지 않습니다.

enter image description here 따라서 다음과 같이 이미지를 변환해야한다고 생각합니다.

d.reshape(3,2,4) 
array([[[ 1, 4, 7, 10], 
     [ 13, 16, 19, 22]],#R layer 
     [[ 2, 5, 8, 11], 
     [ 14, 17, 20, 23]],#G layer 
     [[ 3, 6, 9, 12], 
     [ 15, 18, 21, 24]]])#B layer 

내 이해가 잘못 되었습니까? 지식이 있으면 나를 도와주세요.

아래에 전체 코드를 입력했습니다.

from torch import nn 
    from torch.nn import functional as F 
    from torch.autograd import Variable 
    from sklearn.model_selection import train_test_split 
    import numpy as np 
    from collections import Counter 
    import os 
    import cv2 
    import torch.optim as optim 
    import torch.utils.data 


    def read_labels(file): 
     dic = {} 
     with open(file) as f: 
     reader = f 
     for row in reader: 
      dic[row.split(",")[0]] = row.split(",")[1].rstrip() #rstrip(): eliminate "\n" 
     return dic 

    image_names= os.listdir("../train") 
    label_dic = read_labels("../labels.csv") 

    labels = [] 
    images =[] 

    for name in image_names: 
     images.append(cv2.resize(cv2.imread("../train/"+name,1), (100, 200)).reshape(3,100,200)) 
     labels.append(label_dic[os.path.splitext(name)[0]]) 

    images = np.asarray(images) 


    """ 
    Assign numbers for each labels 
    """ 

    tmp_labels = labels 
    uniq_labels = set(tmp_labels) # eliminate duplication 
    num_breeds = len(Counter(labels)) # number of breeds 
    uniqu_labels_index = dict((label, i) for i, label in enumerate(uniq_labels)) #create dictionary and assign number for each labels 

    labels_num = [uniqu_labels_index[label] for i,label in enumerate(labels)] 
    labels_num = np.array(labels_num) 

    """ 
    Data distribution 
    """ 
    N = len(images) 
    N_train = int(N * 0.7) 
    N_test = int(N*0.2) 

    X_train, X_tmp, Y_train, Y_tmp = train_test_split(images, labels_num, train_size=N_train) 
    X_validation, X_test, Y_validation, Y_test = train_test_split(X_tmp, Y_tmp, test_size=N_test) 

    """ 
    Model Definition 
    """ 


    # CNN Model (2 conv layer) 
    class CNN(nn.Module): 
     def __init__(self): 
      super(CNN, self).__init__() 
      self.layer1 = nn.Sequential(
       nn.Conv2d(3,34, kernel_size=5,padding= 2), 
       nn.Dropout2d(), 
       nn.BatchNorm2d(34), 
       nn.ReLU(), 
       nn.MaxPool2d(2)) 
      self.layer2 = nn.Sequential(
       nn.Conv2d(34, 68, kernel_size=5,padding= 2), 
       nn.BatchNorm2d(68), 
       nn.ReLU(), 
       nn.MaxPool2d(2)) 
      self.fc1 = nn.Linear(1700,300) 
      self.fc2 = nn.Linear(300,num_breeds) 

     def forward(self, x): 
      out = self.layer1(x) 
      #print out.data.shape 
      out = self.layer2(out) 
      #print out.data.shape 
      out = out.view(out.size(0), -1) 
      #print out.data.shape 
      out =self.fc1(out) 
      #out = F.dropout(out) 
      #out = self.fc2(out) 
      return F.log_softmax(out) 

     def accuracy(self,outputs,labels): 
      #for i, (images_val, labels_val) in enumerate(val_loader): 

       # print images.shape 
      # images_val = Variable(images_val).float() 
       # labels_val = Variable(labels_val).float().type(torch.LongTensor) 
       # outputs_val = CNN(images_val) 

      inference = np.argmax(outputs.data.numpy(),axis=1) 
      answers = labels.data.numpy() 
      correction = np.equal(inference,answers) 
      return np.sum(correction)/float(len(correction)) 

    CNN = CNN() 

    """ 
    Training 
    """ 
    batch_size = 100 
    learning_rate =0.01 
    # Data Loader (Input Pipeline) 
    train = torch.utils.data.TensorDataset(torch.from_numpy(X_train), torch.from_numpy(Y_train)) 
    train_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True) 

    val = torch.utils.data.TensorDataset(torch.from_numpy(X_validation), torch.from_numpy(Y_validation)) 
    val_loader = torch.utils.data.DataLoader(val, batch_size=len(X_validation), shuffle=True) 

    test = torch.utils.data.TensorDataset(torch.from_numpy(X_test), torch.from_numpy(Y_test)) 
    test_loader = torch.utils.data.DataLoader(test, batch_size=len(X_test), shuffle=True) 


    criterion = nn.CrossEntropyLoss() 
    optimizer = torch.optim.Adam(CNN.parameters(), lr=learning_rate) 

    for epoch in range(250): # loop over the dataset multiple times 
     running_loss = 0.0 
     for i, (images, labels) in enumerate(train_loader): 

      images = Variable(images).float() 
      labels = Variable(labels).float().type(torch.LongTensor) 
      # Forward + Backward + Optimize 
      optimizer.zero_grad() 
      outputs = CNN(images) 
      loss = criterion(outputs, labels) 
      loss.backward() 
      optimizer.step() 

      running_loss += loss.data[0] 


     accuracy = CNN.accuracy(outputs,labels) 
     print 
     print "epoch :",epoch 
     print 'loss:' ,float(running_loss)/2000 
     print "accuracy :",accuracy 
     running_loss = 0.0 

    print('Finished Training') 
    for i, (images, labels) in enumerate(test_loader): 

      images = Variable(images).float() 
      labels = Variable(labels).float().type(torch.LongTensor) 
      optimizer.zero_grad() 
      outputs = CNN(images) 
    inference = np.argmax(outputs.data.numpy(),axis=1) 
    answers = labels.data.numpy() 
    correction = np.equal(inference,answers) 
    print np.sum(correction)/float(len(correction)) 
+1

로하고있는 경우 출력 형태가 사용되는 것을 볼 수있을 것이다? 변환 된 모양의 RGB 데이터가 어디에 푸시되고 있습니까? 따라야 할 튜토리얼에 대한 링크가 있습니까? 데이터의 모양은 어떤 종류의 "심층 학습"알고리즘이 사용되는지에 달려 있습니다. – jmunsch

답변

0

이 함수는 Numpy에서 가져옵니다.

shape 메서드는 각 레이어에 대해 배열에 몇 개의 요소가 있는지 나타냅니다. 그래서 하여 예제 :

d = array([ 
      [[ 1, 2, 3],[ 4, 5, 6],[ 7, 8, 9],[10, 11, 12]], #1st layer 1st element (4 lists inside with 3 numbers each) 
      [[13, 14, 15],[16, 17, 18], [19, 20, 21],[22, 23, 24]] #1st layer 2nd element (4 lists inside with 3 numbers each) 
     ]) 

제 1 층은 두 개의리스트, 제 4 개리스트를 가지고 세 번째 세 개의 숫자를 갖는다.

reshape(3,2,4)으로 전화를 걸면 첫 번째 레이어에는 3 개의 목록이, 두 번째 레이어에는 2 개의 목록이, 세 번째 레이어에는 4 개의 번호가 제공됩니다.

요소 순서를 변경하지 않고 모양을 변경하기 만하면됩니다. 귀하의 예제에서 imshow으로 수정 된 이미지를 보려고 시도하면 reshape 명령이 이미지를 엉망으로 만든 것을 알 수 있습니다.

시도 : 다음

image = cv2.imread(folder + name, 1) 
cv2.imshow('image',image) 
cv2.waitKey(0) 
cv2.destroyAllWindows() 

:

reshapedimage =cv2.resize(cv2.imread(folder + name, 1), (100, 200)) 
cv2.imshow('image',reshapedimage) 
cv2.waitKey(0) 
cv2.destroyAllWindows() 

당신은 각 명령은 이미지