image_util.py 7.2 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 17 18
#
# 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
from cStringIO import StringIO

19

Z
zhangjinchao01 已提交
20 21 22 23 24 25
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.
    """
26 27 28
    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 已提交
29 30 31
    img = img.resize(resized_size, Image.ANTIALIAS)
    return img

32

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

44

Z
zhangjinchao01 已提交
45 46 47 48 49 50 51 52 53 54 55 56
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:
57 58
        height, width = max(inner_size, im.shape[1]), max(inner_size,
                                                          im.shape[2])
Z
zhangjinchao01 已提交
59 60 61 62
        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]
63
        padded_im[:, startY:endY, startX:endX] = im
Z
zhangjinchao01 已提交
64 65
    else:
        im = im.astype('float32')
66 67
        height, width = max(inner_size, im.shape[0]), max(inner_size,
                                                          im.shape[1])
Z
zhangjinchao01 已提交
68 69 70 71
        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]
72
        padded_im[startY:endY, startX:endX] = im
Z
zhangjinchao01 已提交
73 74 75 76 77 78 79 80
    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:
81
        pic = padded_im[:, startY:endY, startX:endX]
Z
zhangjinchao01 已提交
82
    else:
83
        pic = padded_im[startY:endY, startX:endX]
Z
zhangjinchao01 已提交
84 85 86 87
    if (not test) and (np.random.randint(2) == 0):
        pic = flip(pic)
    return pic

88

Z
zhangjinchao01 已提交
89 90 91 92 93 94
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

95

Z
zhangjinchao01 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109
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,
    and randomy does flipping.
    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()

110

Z
zhangjinchao01 已提交
111 112 113 114 115 116 117 118 119 120
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:
121
        assert (mean_img_size * mean_img_size * 3 == mean.shape[0])
Z
zhangjinchao01 已提交
122
        mean = mean.reshape(3, mean_img_size, mean_img_size)
123 124
        mean = mean[:, border:border + crop_size, border:border +
                    crop_size].astype('float32')
Z
zhangjinchao01 已提交
125
    else:
126
        assert (mean_img_size * mean_img_size == mean.shape[0])
Z
zhangjinchao01 已提交
127
        mean = mean.reshape(mean_img_size, mean_img_size)
128 129
        mean = mean[border:border + crop_size, border:border +
                    crop_size].astype('float32')
Z
zhangjinchao01 已提交
130 131
    return mean

132

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

143

Z
zhangjinchao01 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
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
166 167
    crops_ix[4] = np.tile(im_center, (1, 2)) + np.concatenate(
        [-crop_dims / 2.0, crop_dims / 2.0])
Z
zhangjinchao01 已提交
168 169 170
    crops_ix = np.tile(crops_ix, (2, 1))

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

182

Z
zhangjinchao01 已提交
183
class ImageTransformer:
184 185 186 187 188
    def __init__(self,
                 transpose=None,
                 channel_swap=None,
                 mean=None,
                 is_color=True):
Z
zhangjinchao01 已提交
189 190 191
        self.transpose = transpose
        self.channel_swap = None
        self.mean = None
192
        self.is_color = is_color
Z
zhangjinchao01 已提交
193

194
    def set_transpose(self, order):
Z
zhangjinchao01 已提交
195
        if self.is_color:
196
            assert 3 == len(order)
Z
zhangjinchao01 已提交
197 198
        self.transpose = order

199
    def set_channel_swap(self, order):
Z
zhangjinchao01 已提交
200
        if self.is_color:
201
            assert 3 == len(order)
Z
zhangjinchao01 已提交
202 203 204 205 206
        self.channel_swap = order

    def set_mean(self, mean):
        # mean value, may be one value per channel 
        if mean.ndim == 1:
207 208
            mean = mean[:, np.newaxis, np.newaxis]
        else:
Z
zhangjinchao01 已提交
209 210 211
            # elementwise mean
            if self.is_color:
                assert len(mean.shape) == 3
212
        self.mean = mean
Z
zhangjinchao01 已提交
213 214 215 216 217 218 219 220 221

    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