Does flow_from_directory method in Keras resize the images even if they already match the desired size?

1.2k views Asked by At

In Keras' flow_from_directory an argument sets the desired image size. The default value is 256x256. In my case, other software has already created images that are all 299x299 and are already grayscale. So my question is one of efficiency of Keras/TensorFlow: If I specify image size of 299x299 and I specify color_mode=grayscale, then I hope Keras is not wasting any time to resize and compute grayscale. Is this really the case?

1

There are 1 answers

0
today On BEST ANSWER

The conversions are done only if there is inconsistency. You can easily verify this by inspecting the source code. The function responsible for loading the image and doing necessary conversions is the load_img function (in keras-preprocessing package):

def load_img(path, grayscale=False, color_mode='rgb', target_size=None,
             interpolation='nearest'):
    if grayscale is True:
        warnings.warn('grayscale is deprecated. Please use '
                      'color_mode = "grayscale"')
        color_mode = 'grayscale'
    if pil_image is None:
        raise ImportError('Could not import PIL.Image. '
                          'The use of `load_img` requires PIL.')
    with open(path, 'rb') as f:
        img = pil_image.open(io.BytesIO(f.read()))
        if color_mode == 'grayscale':
            # if image is not already an 8-bit, 16-bit or 32-bit grayscale image
            # convert it to an 8-bit grayscale image.
            if img.mode not in ('L', 'I;16', 'I'):
                img = img.convert('L')
        elif color_mode == 'rgba':
            if img.mode != 'RGBA':
                img = img.convert('RGBA')
        elif color_mode == 'rgb':
            if img.mode != 'RGB':
                img = img.convert('RGB')
        else:
            raise ValueError('color_mode must be "grayscale", "rgb", or "rgba"')
        if target_size is not None:
            width_height_tuple = (target_size[1], target_size[0])
            if img.size != width_height_tuple:
                if interpolation not in _PIL_INTERPOLATION_METHODS:
                    raise ValueError(
                        'Invalid interpolation method {} specified. Supported '
                        'methods are {}'.format(
                            interpolation,
                            ", ".join(_PIL_INTERPOLATION_METHODS.keys())))
                resample = _PIL_INTERPOLATION_METHODS[interpolation]
                img = img.resize(width_height_tuple, resample)
        return img

As you can see above, both color-mode and size conversions are performed if and only if these properties of the loaded image are not consistent with the provided arguments by user (or the default values, if nothing specified by user).