Multiple images input to the same CNN using Conv3d

2020-03-31 02:19发布

I want to enter 8 images at the same time to the same CNN structure using conv3d. my CNN model is as following:

def build(sample, frame, height, width, channels,  classes):
    model = Sequential()
    inputShape = (sample, frame, height, width, channels)
    chanDim = -1

    if K.image_data_format() == "channels_first":
        inputShape = (sample, frame, channels, height, width)
        chanDim = 1


    model.add(Conv3D(32, (3, 3, 3), padding="same", input_shape=inputShape))
    model.add(Activation("relu"))
    model.add(BatchNormalization(axis=chanDim))
    model.add(MaxPooling3D(pool_size=(2, 2, 2), padding="same", data_format="channels_last"))
    model.add(Dropout(0.25))

    model.add(Conv3D(64, (3, 3, 3), padding="same"))
    model.add(Activation("relu"))
    model.add(BatchNormalization(axis=chanDim))
    model.add(MaxPooling3D(pool_size=(2, 2, 2), padding="same", data_format="channels_last"))
    model.add(Dropout(0.25))
    model.add(Flatten())
    model.add(Dense(128))    #(Dense(1024))
    model.add(Activation("relu"))
    model.add(BatchNormalization())
    model.add(Dropout(0.5))

    # softmax classifier
    model.add(Dense(classes))
    model.add(Activation("softmax")

The training of model is as follow:

IMAGE_DIMS = (57, 8, 60, 60, 3) # since I have 460 images so 57 sample with 8 image each
data = np.array(data, dtype="float") / 255.0
labels = np.array(labels)
# binarize the labels
lb = LabelBinarizer()
labels = lb.fit_transform(labels)
# note: data is a list of all dataset images
(trainX, testX, trainY, testY) train_test_split(data, labels, test_size=0.2, random_state=42)                                                                                                          
aug = ImageDataGenerator(rotation_range=25, width_shift_range=0.1, height_shift_range=0.1, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode="nearest")

# initialize the model
model = CNN_Network.build(sample= IMAGE_DIMS[0], frame=IMAGE_DIMS[1],
                      height = IMAGE_DIMS[2], width=IMAGE_DIMS[3],
                      channels=IMAGE_DIMS[4], classes=len(lb.classes_))

opt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)
model.compile(loss="categorical_crossentropy", optimizer= opt, metrics=["accuracy"])

# train the network
model.fit_generator(
aug.flow(trainX, trainY, batch_size=BS),
validation_data=(testX, testY),
steps_per_epoch=len(trainX) // BS,
epochs=EPOCHS, verbose=1)

I have confused with the input_shape, I know Conv3D require 5D input, the input is 4D with batch added from keras, but I have the following error:

ValueError: Error when checking input: expected conv3d_1_input to have 5 dimensions, but got array with shape (92, 60, 60, 3)

Can anyone please help me what can I do? what is the 92 resulted, I determine input_shape with (57, 8, 60, 60, 3). And what is my input_shape should become to get 8 colored images input to the same model at the same time.

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-03-31 02:54

Here is a custom imagedatagenerator for 5D input to Conv3D nets. Hope it helps. Here is an example on how to use it:

from tweaked_ImageGenerator_v2 import ImageDataGenerator
datagen = ImageDataGenerator()
train_data=datagen.flow_from_directory('path/to/data', target_size=(x, y), batch_size=32, frames_per_step=4)

OR

You can build your own 5D tensor:

frames_folder = 'path/to/folder'
X_data = []
y_data = []
list_of_sent = os.listdir(frames_folder)
print (list_of_sent)
class_num = 0
time_steps = 0  
frames = []
for i in list_of_sent:
    classes_folder = str(frames_folder + '/' + i) #path to each class
    print (classes_folder)
    list_of_frames = os.listdir(classes_folder)
    time_steps= 0
    frames = []
    for filename in  sorted(list_of_frames):   
        if ( time_steps == 8 ):
            X_data.append(frames) #appending each tensor of 8 frames resized to 110,110
            y_data.append(class_num) #appending a class label to the set of 8 frames
            j = 0  
            frames = []
        else:
            time_steps+=1
            filename = cv2.imread(vid + '/' + filename)
            filename = cv2.resize(filename,(110, 110),interpolation=cv2.INTER_AREA)
            frames.append(filename)


    class_num+=1
X_data = np.array(X_data)
y_data = np.array(y_data)

For the snippet above, the folder structure must be like that:

    data/
        class0/
            img001.jpg
            img002.jpg
            ...
        class1/
            img001.jpg
            img002.jpg
            ...
查看更多
登录 后发表回答