2017-03-22 3 views
1

test-images에 대한 CNN 모델의 정확성을 테스트하고 싶습니다. 다음은 mha 형식의 Ground-truth 이미지를 png 형식으로 변환하는 코드입니다.Keras wrong image size

def save_labels(fns): 
    ''' 
    INPUT list 'fns': filepaths to all labels 
    ''' 
    progress.currval = 0 
    for label_idx in progress(xrange(len(fns))): 
     slices = io.imread(fns[label_idx], plugin = 'simpleitk') 
     for slice_idx in xrange(len(slices)): 
     ''' 
     commented code in order to reshape the image slices. I tried reshaping but it did not work 
     strip=slices[slice_idx].reshape(1200,240) 
     if np.max(strip)!=0: 
     strip /= np.max(strip) 
      if np.min(strip)<=-1: 
     strip/=abs(np.min(strip)) 
     ''' 
     io.imsave('Labels2/{}_{}L.png'.format(label_idx, slice_idx), slices[slice_idx]) 

이 코드는 240x240 이미지를 png 형식으로 생성합니다. 그러나 대부분은 낮은 콘트라스트 또는 완전히 검은 색입니다. 계속해서, 나는 라벨 이미지의 클래스를 아는 계산을 위해이 이미지들을 함수로 전달한다.

def predict_image(self, test_img, show=False): 
     ''' 
     predicts classes of input image 
     INPUT (1) str 'test_image': filepath to image to predict on 
       (2) bool 'show': True to show the results of prediction, False to return prediction 
     OUTPUT (1) if show == False: array of predicted pixel classes for the center 208 x 208 pixels 
       (2) if show == True: displays segmentation results 
     ''' 
     imgs = io.imread(test_img,plugin='simpleitk').astype('float').reshape(5,240,240) 
     plist = [] 

     # create patches from an entire slice 
     for img in imgs[:-1]: 
      if np.max(img) != 0: 
       img /= np.max(img) 
      p = extract_patches_2d(img, (33,33)) 
      plist.append(p) 
     patches = np.array(zip(np.array(plist[0]), np.array(plist[1]), np.array(plist[2]), np.array(plist[3]))) 

     # predict classes of each pixel based on model 
     full_pred = keras.utils.np_utils.probas_to_classes(self.model_comp.predict(patches)) 
     fp1 = full_pred.reshape(208,208) 
     if show: 
      io.imshow(fp1) 
      plt.show 
     else: 
      return fp1 

나는 ValueError: cannot reshape array of size 172800 into shape (5,240,240)을 얻고 있습니다. 나는 5를 3으로 변경하여 3X240X240 = 172800이되도록했습니다. 하지만 그때 새로운 문제가 ValueError: Error when checking : expected convolution2d_input_1 to have 4 dimensions, but got array with shape (43264, 33, 33)입니다.

내 모델은 다음과 같습니다 : 나는 keras 1.2.2을 사용하고

 single = Sequential() 
     single.add(Convolution2D(self.n_filters[0], self.k_dims[0], self.k_dims[0], border_mode='valid', W_regularizer=l1l2(l1=self.w_reg, l2=self.w_reg), input_shape=(self.n_chan,33,33))) 
     single.add(Activation(self.activation)) 
     single.add(BatchNormalization(mode=0, axis=1)) 
     single.add(MaxPooling2D(pool_size=(2,2), strides=(1,1))) 
     single.add(Dropout(0.5)) 
     single.add(Convolution2D(self.n_filters[1], self.k_dims[1], self.k_dims[1], activation=self.activation, border_mode='valid', W_regularizer=l1l2(l1=self.w_reg, l2=self.w_reg))) 
     single.add(BatchNormalization(mode=0, axis=1)) 
     single.add(MaxPooling2D(pool_size=(2,2), strides=(1,1))) 
     single.add(Dropout(0.5)) 
     single.add(Convolution2D(self.n_filters[2], self.k_dims[2], self.k_dims[2], activation=self.activation, border_mode='valid', W_regularizer=l1l2(l1=self.w_reg, l2=self.w_reg))) 
     single.add(BatchNormalization(mode=0, axis=1)) 
     single.add(MaxPooling2D(pool_size=(2,2), strides=(1,1))) 
     single.add(Dropout(0.5)) 
     single.add(Convolution2D(self.n_filters[3], self.k_dims[3], self.k_dims[3], activation=self.activation, border_mode='valid', W_regularizer=l1l2(l1=self.w_reg, l2=self.w_reg))) 
     single.add(Dropout(0.25)) 

     single.add(Flatten()) 
     single.add(Dense(5)) 
     single.add(Activation('softmax')) 

     sgd = SGD(lr=0.001, decay=0.01, momentum=0.9) 
     single.compile(loss='categorical_crossentropy', optimizer='sgd') 
     print 'Done.' 
     return single 

. 배경 정보는 이전 게시물의 herehere을 참조하십시오 (상기 코드의 full_predict가 this 변경으로 인한 것입니까?). 이 특정 크기가 33,33과 같은 이유를 알고 싶다면 this을 참조하십시오.

답변

1

패치 배열의 모양을 확인해야합니다. 4 차원 (nrBatches, nrChannels, Width, Height)이 있어야합니다. 오류 메시지에 따르면 3 차원 만 있습니다. 따라서 채널 측정 기준을 일괄 측정 기준과 병합 한 것으로 보입니다.