Keras错误的图像大小

时间:2017-03-22 10:28:05

标签: python tensorflow deep-learning keras convolution

我想测试test-images的CNN模型的准确性。以下是将mha格式的地面实况图像转换为png格式的代码。

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])

此代码以png格式生成240 X 240图像。然而,大多数是低对比度或完全变黑。继续前进,现在我将这些图像传递给计算知道标记图像类别的函数。

   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)

我的模型看起来像这样:

        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

我正在使用keras 1.2.2。有关背景信息,请参阅我之前发布的帖子中的herehere(这是由于上述代码中的this更改为full_predict)。请参考this了解为何这些特定尺寸如33,33。

1 个答案:

答案 0 :(得分:1)

您应该检查补丁阵列的形状。这应该有4个维度(nrBatches,nrChannels,Width,Height)。根据您的错误消息,只有3个维度。因此,您似乎将渠道维度与批量维度合并。