Copyright 2018 Google Inc.

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

https://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.

Image Preprocessing

In this tutorial, we are going to use the Pillow python lirbrary to show how to apply basic transformations on images. You can safely skip this tutorial if you are already familiar with Pillow.

First of all, let's import all the libraries we need.


In [44]:
from google.colab import files
from io import BytesIO
# Display images.
from IPython.display import display
from PIL import Image, ImageEnhance

Next, let's upload a PNG image which we will apply all kinds of transformations on, and resize it to 500x500.


In [0]:
# Please assign the real file name of the image to image_name.
image_name = ''

uploaded_files = files.upload()

size = (500, 500) # (width, height)
image = Image.open(BytesIO(uploaded_files[image_name])).resize(size)

display(image)

Now that we have the image uploaded, let's try rotate the image by 90 degrees cunter-clockwise.


In [0]:
image = image.transpose(Image.ROTATE_90)


display(image)

Now let's flip the image horizontally.


In [0]:
image = image.transpose(Image.FLIP_LEFT_RIGHT)

display(image)

As a next step, let's adjust the contrast of the image. The base value is 1 and here we are increasing it by 20%.


In [0]:
contrast = ImageEnhance.Contrast(image)
image = contrast.enhance(1.2)

display(image)

And brightness and sharpness.


In [0]:
brightness = ImageEnhance.Brightness(image)
image = brightness.enhance(1.1)

display(image)

In [0]:
sharpness = ImageEnhance.Sharpness(image)
image = sharpness.enhance(1.2)

display(image)

There are a whole lot more transformations we can make on images, please take a look at the official documentation if you'd like to know more.