重塑张量的正确方法是什么?

时间:2018-09-28 04:59:38

标签: python tensorflow keras scikit-image

以下代码用于胸部X光检查的肺部分割(2D)。它应该使用经过训练的模型“ trained_model.hdf5”从胸部X射线生成肺罩。在提供胸部X射线作为输入时,它应该能够识别出哪些是肺部,并相应地创建一个单独的肺部遮罩。 print (df) student_id date1 project_id1 date2 project_id2 datelast \ 0 1 2018-01-01 15.0 2018-01-01 17.0 2018-03-03 1 2 2018-02-03 3.0 2018-04-03 4.0 2018-05-03 2 3 2018-07-03 7.0 2018-08-03 8.0 NaT 3 4 2018-09-03 2.0 NaT NaN NaT projectlast 0 12.0 1 4.0 2 NaN 3 NaN 包含经过JSRT数据集训练的模型。

trained_model.hdf5

但是我收到此错误:

#from load_data import loadDataJSRT, loadDataMontgomery

import numpy as np
import pandas as pd
from keras.models import load_model
from skimage import morphology, io, color, exposure, img_as_float, transform
from keras.preprocessing.image import ImageDataGenerator

def loadDataGeneral(df, path, im_shape):
    X = []
    for i, item in df.iterrows():
        img = img_as_float(io.imread(path + str(item[0])))
        #mask = io.imread(path + item[1])
        img = transform.resize(img, im_shape)
        img = exposure.equalize_hist(img)
        img = np.expand_dims(img, -1)
        #mask = transform.resize(mask, im_shape)
        #mask = np.expand_dims(mask, -1)
        X.append(img)
        #y.append(mask)
    X = np.array(X)
    #y = np.array(y)
    X -= X.mean()
    X /= X.std()

    print( '### Dataset loaded')
    print( '\t{}'.format(path))
    #print( '\t{}\t{}'.format(X.shape, y.shape))
    #print( '\tX:{:.1f}-{:.1f}\ty:{:.1f}-{:.1f}\n'.format(X.min(), X.max(), y.min(), y.max()))
    print( '\tX.mean = {}, X.std = {}'.format(X.mean(), X.std()))
    return X



if __name__ == '__main__':

    # Path to csv-file. File should contain X-ray filenames as first column,
    # mask filenames as second column.
    csv_path = 'idx.csv'
    # Path to the folder with images. Images will be read from path + path_from_csv
    path = 'Data/'

    df = pd.read_csv(csv_path)

    # Load test data
    im_shape = (256, 256)
    X = loadDataGeneral(df, path, im_shape)
    #print('***X= ',X)
    n_test = X.shape[0]
    inp_shape = X[0].shape

    # Load model
    model_name = 'trained_model.hdf5'
    UNet = load_model(model_name)

    # For inference standard keras ImageGenerator is used.
    test_gen = ImageDataGenerator(rescale=1.)

    ious = np.zeros(n_test)
    dices = np.zeros(n_test)

    i = 0

    print("TEST_GEN ",test_gen)

    print(len(X))
    for xx in test_gen.flow(X, batch_size=1):
        xx = xx[0:4]
        img = exposure.rescale_intensity(np.squeeze(xx), out_range=(0,1))
        pred = UNet.predict(xx)[..., 0].reshape(inp_shape[:2])
        #mask = yy[..., 0].reshape(inp_shape[:2])

        # Binarize masks
        #gt = mask > 0.5
        pr = pred > 0.5

        # Remove regions smaller than 2% of the image
        pr = remove_small_regions(pr, 0.02 * np.prod(im_shape))

        io.imsave('results/{}'.format(df.iloc[i][0]), masked(img, pr, 1))

        #ious[i] = IoU(gt, pr)
        #dices[i] = Dice(gt, pr)
        #print(df.iloc[i][0], ious[i], dices[i])

        i += 1
        if i == n_test:
            break

如何重塑张量?我究竟做错了什么 ?

1 个答案:

答案 0 :(得分:1)

ImageDataGenerator期望输入的形状为(samples, height, width, channels),但在您的情况下,这是一个额外的维度。但是输入X的形状为(samples, height, width, channels, 1),因此您需要首先删除最后一个尺寸。

要回答有关重塑张量的问题,有多种方法可以执行。 尝试

X = X[:,:,:,0]

OR

X = X[:,:,:,-1]

OR

X = tf.reshape(X,[5,256,256,3])