def image_generator_from_dataframe(dataframe,
                                   img_size,
                                   batch_size,
                                   cls_labels,
                                   datagen,
                                   color_mode='rgb'):
    """
    Creates a generator that loads images from information in a pandas dataframe.

    The dataframe must have at least two columns:
    - "filename" with the absolute path to the file
    - "cls" with the class label of each image (text)

    Images will be preprocessed using an ImageDataGenerator, resized to a fixed shape and converted to grayscale if desired.

    :param dataframe: Pandas dataframe with the image information
    :param img_size: Shape of to resize the images to, e.g. (128, 128)
    :param batch_size: Size of the generator batch
    :param cls_labels: List containing each class label
    :param datagen: The ImageDataGenerator for preprocessing
    :param color_mode: 'rgb' or 'grayscale' to produce 3 or 1 channel images, respectively
    :return:
    """
    return datagen.flow_from_dataframe(
        dataframe,
        x_col="filenames",
        y_col="cls",
        classes=cls_labels,
        target_size=img_size,
        batch_size=batch_size,
        color_mode=color_mode,
        interpolation='bilinear',
        class_mode='categorical')