Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions research/delf/delf/python/datasets/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# Lint as: python3
# Copyright 2021 The TensorFlow Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Supporting functions for data loading."""

import numpy as np
from PIL import Image

import tensorflow as tf
from delf.python import utils as image_loading_utils


def pil_imagenet_loader(path, imsize, bounding_box=None, normalize=True):
"""Pillow loader for the images.

Args:
path: Path to image to be loaded.
imsize: Integer, defines the maximum size of longer image side.
bounding_box: (x1,y1,x2,y2) tuple to crop the query image.
normalize: Bool, whether to normalize the image.

Returns:
image: `Tensor`, image in ImageNet suitable format.
"""
img = image_loading_utils.RgbLoader(path)

if bounding_box is not None:
imfullsize = max(img.size)
img = img.crop(bounding_box)
imsize = imsize * max(img.size) / imfullsize

# Unlike `resize`, `thumbnail` resizes to the largest size that preserves
# the aspect ratio, making sure that the output image does not exceed the
# original image size and the size specified in the arguments of thumbnail.
img.thumbnail((imsize, imsize), Image.ANTIALIAS)
img = np.array(img)

if normalize:
# Preprocessing for ImageNet data. Converts the images from RGB to BGR,
# then zero-centers each color channel with respect to the ImageNet
# dataset, without scaling.
tf.keras.applications.imagenet_utils.preprocess_input(img, mode='caffe')

return img


def default_loader(path, imsize, bounding_box=None, normalize=True):
"""Default loader for the images is using Pillow.

Args:
path: Path to image to be loaded.
imsize: Integer, defines the maximum size of longer image side.
bounding_box: (x1,y1,x2,y2) tuple to crop the query image.

Returns:
image: `Tensor`, image in ImageNet suitable format.
"""
img = pil_imagenet_loader(path, imsize, bounding_box, normalize)
return img
76 changes: 76 additions & 0 deletions research/delf/delf/python/datasets/utils_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Lint as: python3
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for dataset utilities."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os

from absl import flags
import numpy as np
from PIL import Image
import tensorflow as tf

from delf.python.datasets import utils as image_loading_utils

FLAGS = flags.FLAGS


class UtilsTest(tf.test.TestCase):

def testDefaultLoader(self):
# Create a dummy image.
dummy_image = np.random.rand(1024, 750, 3) * 255
img_out = Image.fromarray(dummy_image.astype('uint8')).convert('RGB')
filename = os.path.join(FLAGS.test_tmpdir, 'test_image.png')
# Save the dummy image.
img_out.save(filename)

max_img_size = 1024
# Load the saved dummy image.
img = image_loading_utils.default_loader(filename, imsize=max_img_size,
normalize=False)

# Make sure the values are the same before and after loading.
self.assertAllEqual(np.array(img_out), img)

self.assertAllLessEqual(tf.shape(img), max_img_size)

def testDefaultLoaderWithBoundingBox(self):
# Create a dummy image.
dummy_image = np.random.rand(1024, 750, 3) * 255
img_out = Image.fromarray(dummy_image.astype('uint8')).convert('RGB')
filename = os.path.join(FLAGS.test_tmpdir, 'test_image.png')
# Save the dummy image.
img_out.save(filename)

max_img_size = 1024
# Load the saved dummy image.
expected_size = 400
img = image_loading_utils.default_loader(filename, imsize=max_img_size,
bounding_box=[120, 120,
120 + expected_size,
120 + expected_size],
normalize=False)

# Check the shape.
self.assertAllEqual(tf.shape(img), [expected_size, expected_size, 3])


if __name__ == '__main__':
tf.test.main()