Skip to content

Commit 7899ccd

Browse files
authored
Dataset utilities added. (#9796)
1 parent e9ca9ff commit 7899ccd

File tree

2 files changed

+147
-0
lines changed

2 files changed

+147
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# Lint as: python3
2+
# Copyright 2021 The TensorFlow Authors All Rights Reserved.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
# ==============================================================================
16+
"""Supporting functions for data loading."""
17+
18+
import numpy as np
19+
from PIL import Image
20+
21+
import tensorflow as tf
22+
from delf.python import utils as image_loading_utils
23+
24+
25+
def pil_imagenet_loader(path, imsize, bounding_box=None, normalize=True):
26+
"""Pillow loader for the images.
27+
28+
Args:
29+
path: Path to image to be loaded.
30+
imsize: Integer, defines the maximum size of longer image side.
31+
bounding_box: (x1,y1,x2,y2) tuple to crop the query image.
32+
normalize: Bool, whether to normalize the image.
33+
34+
Returns:
35+
image: `Tensor`, image in ImageNet suitable format.
36+
"""
37+
img = image_loading_utils.RgbLoader(path)
38+
39+
if bounding_box is not None:
40+
imfullsize = max(img.size)
41+
img = img.crop(bounding_box)
42+
imsize = imsize * max(img.size) / imfullsize
43+
44+
# Unlike `resize`, `thumbnail` resizes to the largest size that preserves
45+
# the aspect ratio, making sure that the output image does not exceed the
46+
# original image size and the size specified in the arguments of thumbnail.
47+
img.thumbnail((imsize, imsize), Image.ANTIALIAS)
48+
img = np.array(img)
49+
50+
if normalize:
51+
# Preprocessing for ImageNet data. Converts the images from RGB to BGR,
52+
# then zero-centers each color channel with respect to the ImageNet
53+
# dataset, without scaling.
54+
tf.keras.applications.imagenet_utils.preprocess_input(img, mode='caffe')
55+
56+
return img
57+
58+
59+
def default_loader(path, imsize, bounding_box=None, normalize=True):
60+
"""Default loader for the images is using Pillow.
61+
62+
Args:
63+
path: Path to image to be loaded.
64+
imsize: Integer, defines the maximum size of longer image side.
65+
bounding_box: (x1,y1,x2,y2) tuple to crop the query image.
66+
67+
Returns:
68+
image: `Tensor`, image in ImageNet suitable format.
69+
"""
70+
img = pil_imagenet_loader(path, imsize, bounding_box, normalize)
71+
return img
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# Lint as: python3
2+
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
# ==============================================================================
16+
"""Tests for dataset utilities."""
17+
18+
from __future__ import absolute_import
19+
from __future__ import division
20+
from __future__ import print_function
21+
22+
import os
23+
24+
from absl import flags
25+
import numpy as np
26+
from PIL import Image
27+
import tensorflow as tf
28+
29+
from delf.python.datasets import utils as image_loading_utils
30+
31+
FLAGS = flags.FLAGS
32+
33+
34+
class UtilsTest(tf.test.TestCase):
35+
36+
def testDefaultLoader(self):
37+
# Create a dummy image.
38+
dummy_image = np.random.rand(1024, 750, 3) * 255
39+
img_out = Image.fromarray(dummy_image.astype('uint8')).convert('RGB')
40+
filename = os.path.join(FLAGS.test_tmpdir, 'test_image.png')
41+
# Save the dummy image.
42+
img_out.save(filename)
43+
44+
max_img_size = 1024
45+
# Load the saved dummy image.
46+
img = image_loading_utils.default_loader(filename, imsize=max_img_size,
47+
normalize=False)
48+
49+
# Make sure the values are the same before and after loading.
50+
self.assertAllEqual(np.array(img_out), img)
51+
52+
self.assertAllLessEqual(tf.shape(img), max_img_size)
53+
54+
def testDefaultLoaderWithBoundingBox(self):
55+
# Create a dummy image.
56+
dummy_image = np.random.rand(1024, 750, 3) * 255
57+
img_out = Image.fromarray(dummy_image.astype('uint8')).convert('RGB')
58+
filename = os.path.join(FLAGS.test_tmpdir, 'test_image.png')
59+
# Save the dummy image.
60+
img_out.save(filename)
61+
62+
max_img_size = 1024
63+
# Load the saved dummy image.
64+
expected_size = 400
65+
img = image_loading_utils.default_loader(filename, imsize=max_img_size,
66+
bounding_box=[120, 120,
67+
120 + expected_size,
68+
120 + expected_size],
69+
normalize=False)
70+
71+
# Check the shape.
72+
self.assertAllEqual(tf.shape(img), [expected_size, expected_size, 3])
73+
74+
75+
if __name__ == '__main__':
76+
tf.test.main()

0 commit comments

Comments
 (0)