image_util.py 7.3 KB
Newer Older
1
# Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#
# 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.

import numpy as np
from PIL import Image
M
minqiyang 已提交
17
from six.moves import cStringIO as StringIO
Z
zhangjinchao01 已提交
18

19 20
__all__ = []

Q
qijun 已提交
21

Z
zhangjinchao01 已提交
22 23 24 25 26 27
def resize_image(img, target_size):
    """
    Resize an image so that the shorter edge has length target_size.
    img: the input image to be resized.
    target_size: the target resized image size.
    """
Q
qijun 已提交
28 29 30
    percent = (target_size / float(min(img.size[0], img.size[1])))
    resized_size = int(round(img.size[0] * percent)), int(
        round(img.size[1] * percent))
Z
zhangjinchao01 已提交
31 32 33
    img = img.resize(resized_size, Image.ANTIALIAS)
    return img

Q
qijun 已提交
34

Z
zhangjinchao01 已提交
35 36 37 38
def flip(im):
    """
    Return the flipped image.
    Flip an image along the horizontal direction.
G
Galden 已提交
39
    im: input image, (K x H x W) ndarrays
Z
zhangjinchao01 已提交
40 41 42 43 44 45
    """
    if len(im.shape) == 3:
        return im[:, :, ::-1]
    else:
        return im[:, ::-1]

Q
qijun 已提交
46

Z
zhangjinchao01 已提交
47 48 49 50 51 52 53 54 55 56 57 58
def crop_img(im, inner_size, color=True, test=True):
    """
    Return cropped image.
    The size of the cropped image is inner_size * inner_size.
    im: (K x H x W) ndarrays
    inner_size: the cropped image size.
    color: whether it is color image.
    test: whether in test mode.
      If False, does random cropping and flipping.
      If True, crop the center of images.
    """
    if color:
Q
qijun 已提交
59 60
        height, width = max(inner_size, im.shape[1]), max(inner_size,
                                                          im.shape[2])
Z
zhangjinchao01 已提交
61 62 63 64
        padded_im = np.zeros((3, height, width))
        startY = (height - im.shape[1]) / 2
        startX = (width - im.shape[2]) / 2
        endY, endX = startY + im.shape[1], startX + im.shape[2]
Q
qijun 已提交
65
        padded_im[:, startY:endY, startX:endX] = im
Z
zhangjinchao01 已提交
66 67
    else:
        im = im.astype('float32')
Q
qijun 已提交
68 69
        height, width = max(inner_size, im.shape[0]), max(inner_size,
                                                          im.shape[1])
Z
zhangjinchao01 已提交
70 71 72 73
        padded_im = np.zeros((height, width))
        startY = (height - im.shape[0]) / 2
        startX = (width - im.shape[1]) / 2
        endY, endX = startY + im.shape[0], startX + im.shape[1]
Q
qijun 已提交
74
        padded_im[startY:endY, startX:endX] = im
Z
zhangjinchao01 已提交
75 76 77 78 79 80 81 82
    if test:
        startY = (height - inner_size) / 2
        startX = (width - inner_size) / 2
    else:
        startY = np.random.randint(0, height - inner_size + 1)
        startX = np.random.randint(0, width - inner_size + 1)
    endY, endX = startY + inner_size, startX + inner_size
    if color:
Q
qijun 已提交
83
        pic = padded_im[:, startY:endY, startX:endX]
Z
zhangjinchao01 已提交
84
    else:
Q
qijun 已提交
85
        pic = padded_im[startY:endY, startX:endX]
Z
zhangjinchao01 已提交
86 87 88 89
    if (not test) and (np.random.randint(2) == 0):
        pic = flip(pic)
    return pic

Q
qijun 已提交
90

Z
zhangjinchao01 已提交
91 92 93 94 95 96
def decode_jpeg(jpeg_string):
    np_array = np.array(Image.open(StringIO(jpeg_string)))
    if len(np_array.shape) == 3:
        np_array = np.transpose(np_array, (2, 0, 1))
    return np_array

Q
qijun 已提交
97

Z
zhangjinchao01 已提交
98 99 100 101 102
def preprocess_img(im, img_mean, crop_size, is_train, color=True):
    """
    Does data augmentation for images.
    If is_train is false, cropping the center region from the image.
    If is_train is true, randomly crop a region from the image,
T
tianshuo78520a 已提交
103
    and random does flipping.
Z
zhangjinchao01 已提交
104 105 106 107 108 109 110 111
    im: (K x H x W) ndarrays
    """
    im = im.astype('float32')
    test = not is_train
    pic = crop_img(im, crop_size, color, test)
    pic -= img_mean
    return pic.flatten()

Q
qijun 已提交
112

Z
zhangjinchao01 已提交
113 114 115 116 117 118 119 120 121 122
def load_meta(meta_path, mean_img_size, crop_size, color=True):
    """
    Return the loaded meta file.
    Load the meta image, which is the mean of the images in the dataset.
    The mean image is subtracted from every input image so that the expected mean
    of each input image is zero.
    """
    mean = np.load(meta_path)['data_mean']
    border = (mean_img_size - crop_size) / 2
    if color:
Q
qijun 已提交
123
        assert (mean_img_size * mean_img_size * 3 == mean.shape[0])
Z
zhangjinchao01 已提交
124
        mean = mean.reshape(3, mean_img_size, mean_img_size)
Q
qijun 已提交
125 126
        mean = mean[:, border:border + crop_size, border:border +
                    crop_size].astype('float32')
Z
zhangjinchao01 已提交
127
    else:
Q
qijun 已提交
128
        assert (mean_img_size * mean_img_size == mean.shape[0])
Z
zhangjinchao01 已提交
129
        mean = mean.reshape(mean_img_size, mean_img_size)
Q
qijun 已提交
130 131
        mean = mean[border:border + crop_size, border:border +
                    crop_size].astype('float32')
Z
zhangjinchao01 已提交
132 133
    return mean

Q
qijun 已提交
134

Z
zhangjinchao01 已提交
135 136
def load_image(img_path, is_color=True):
    """
M
minqiyang 已提交
137
    Load image and return.
Z
zhangjinchao01 已提交
138 139 140 141 142 143 144
    img_path: image path.
    is_color: is color image or not.
    """
    img = Image.open(img_path)
    img.load()
    return img

Q
qijun 已提交
145

Z
zhangjinchao01 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
def oversample(img, crop_dims):
    """
    image : iterable of (H x W x K) ndarrays
    crop_dims: (height, width) tuple for the crops.
    Returned data contains ten crops of input image, namely,
    four corner patches and the center patch as well as their
    horizontal reflections.
    """
    # Dimensions and center.
    im_shape = np.array(img[0].shape)
    crop_dims = np.array(crop_dims)
    im_center = im_shape[:2] / 2.0

    # Make crop coordinates
    h_indices = (0, im_shape[0] - crop_dims[0])
    w_indices = (0, im_shape[1] - crop_dims[1])
    crops_ix = np.empty((5, 4), dtype=int)
    curr = 0
    for i in h_indices:
        for j in w_indices:
            crops_ix[curr] = (i, j, i + crop_dims[0], j + crop_dims[1])
            curr += 1
Q
qijun 已提交
168 169
    crops_ix[4] = np.tile(im_center, (1, 2)) + np.concatenate(
        [-crop_dims / 2.0, crop_dims / 2.0])
Z
zhangjinchao01 已提交
170 171 172
    crops_ix = np.tile(crops_ix, (2, 1))

    # Extract crops
Q
qijun 已提交
173 174 175
    crops = np.empty(
        (10 * len(img), crop_dims[0], crop_dims[1], im_shape[-1]),
        dtype=np.float32)
Z
zhangjinchao01 已提交
176 177 178 179 180
    ix = 0
    for im in img:
        for crop in crops_ix:
            crops[ix] = im[crop[0]:crop[2], crop[1]:crop[3], :]
            ix += 1
Q
qijun 已提交
181
        crops[ix - 5:ix] = crops[ix - 5:ix, :, ::-1, :]  # flip for mirrors
Z
zhangjinchao01 已提交
182 183
    return crops

Q
qijun 已提交
184

Z
zhangjinchao01 已提交
185
class ImageTransformer:
Q
qijun 已提交
186 187 188 189 190 191
    def __init__(self,
                 transpose=None,
                 channel_swap=None,
                 mean=None,
                 is_color=True):
        self.is_color = is_color
192 193 194
        self.set_transpose(transpose)
        self.set_channel_swap(channel_swap)
        self.set_mean(mean)
Z
zhangjinchao01 已提交
195

Q
qijun 已提交
196
    def set_transpose(self, order):
197 198 199
        if order is not None:
            if self.is_color:
                assert 3 == len(order)
Z
zhangjinchao01 已提交
200 201
        self.transpose = order

Q
qijun 已提交
202
    def set_channel_swap(self, order):
203 204 205
        if order is not None:
            if self.is_color:
                assert 3 == len(order)
Z
zhangjinchao01 已提交
206 207 208
        self.channel_swap = order

    def set_mean(self, mean):
209
        if mean is not None:
M
minqiyang 已提交
210
            # mean value, may be one value per channel
211 212 213 214 215 216
            if mean.ndim == 1:
                mean = mean[:, np.newaxis, np.newaxis]
            else:
                # elementwise mean
                if self.is_color:
                    assert len(mean.shape) == 3
Q
qijun 已提交
217
        self.mean = mean
Z
zhangjinchao01 已提交
218 219 220 221 222 223 224 225 226

    def transformer(self, data):
        if self.transpose is not None:
            data = data.transpose(self.transpose)
        if self.channel_swap is not None:
            data = data[self.channel_swap, :, :]
        if self.mean is not None:
            data -= self.mean
        return data