{"id":1905,"date":"2019-03-21T18:00:08","date_gmt":"2019-03-21T18:00:08","guid":{"rendered":"https:\/\/www.aiproblog.com\/index.php\/2019\/03\/21\/how-to-load-and-manipulate-images-for-deep-learning-in-python-with-pil-pillow\/"},"modified":"2019-03-21T18:00:08","modified_gmt":"2019-03-21T18:00:08","slug":"how-to-load-and-manipulate-images-for-deep-learning-in-python-with-pil-pillow","status":"publish","type":"post","link":"https:\/\/www.aiproblog.com\/index.php\/2019\/03\/21\/how-to-load-and-manipulate-images-for-deep-learning-in-python-with-pil-pillow\/","title":{"rendered":"How to Load and Manipulate Images for Deep Learning in Python With PIL\/Pillow"},"content":{"rendered":"<p>Author: Jason Brownlee<\/p>\n<div>\n<p>Before you can develop predictive models for image data, you must learn how to load and manipulate images and photographs.<\/p>\n<p>The most popular and de facto standard library in Python for loading and working with image data is Pillow. Pillow is an updated version of the Python Image Library, or PIL, and supports a range of simple and sophisticated image manipulation functionality. It is also the basis for simple image support in other Python libraries such as SciPy and Matplotlib.<\/p>\n<p>In this tutorial, you will discover how to load and manipulate image data using the Pillow Python library.<\/p>\n<p>After completing this tutorial, you will know:<\/p>\n<ul>\n<li>How to install the Pillow library and confirm it is working correctly.<\/li>\n<li>How to load images from file, convert loaded images to NumPy arrays, and save images in new formats.<\/li>\n<li>How to perform basic transforms to image data such as resize, flips, rotations, and cropping.<\/li>\n<\/ul>\n<p>Let\u2019s get started.<\/p>\n<h2>Tutorial Overview<\/h2>\n<p>This tutorial is divided into six parts; they are:<\/p>\n<ol>\n<li>How to Install Pillow<\/li>\n<li>How to Load and Display Images<\/li>\n<li>How to Convert Images to NumPy Arrays and Back<\/li>\n<li>How to Save Images to File<\/li>\n<li>How to Resize Images<\/li>\n<li>How to Flip, Rotate, and Crop Images<\/li>\n<\/ol>\n<h2>How to Install Pillow<\/h2>\n<p>The <a href=\"http:\/\/www.pythonware.com\/products\/pil\/\">Python Imaging Library<\/a>, or PIL for short, is an open source library for loading and manipulating images.<\/p>\n<p>It was developed and made available more than 25 years ago and has become a de facto standard API for working with images in Python. The library is now defunct and no longer updated and does not support Python 3.<\/p>\n<p><a href=\"https:\/\/python-pillow.org\/\">Pillow<\/a> is a PIL library that supports Python 3 and is the preferred modern library for image manipulation in Python. It is even required for simple image loading and saving in other Python scientific libraries such as SciPy and Matplotlib.<\/p>\n<p>The Pillow library is installed as a part of most SciPy installations; for example, if you are using Anaconda.<\/p>\n<p>For help setting up your SciPy environment, see the step-by-step tutorial:<\/p>\n<ul>\n<li><a href=\"https:\/\/machinelearningmastery.com\/setup-python-environment-machine-learning-deep-learning-anaconda\/\">How to Set Up a Python Environment for Machine Learning and Deep Learning With Anaconda<\/a><\/li>\n<\/ul>\n<p>If you manage the installation of Python software packages yourself for your workstation, you can easily install Pillow using pip; for example:<\/p>\n<pre class=\"crayon-plain-tag\">sudo pip install Pillow<\/pre>\n<p>For more help installing Pillow manually, see:<\/p>\n<ul>\n<li><a href=\"https:\/\/pillow.readthedocs.io\/en\/stable\/installation.html\">Pillow Installation Instructions<\/a><\/li>\n<\/ul>\n<p>Pillow is built on top of the older PIL and you can confirm that the library was installed correctly by printing the version number; for example:<\/p>\n<pre class=\"crayon-plain-tag\"># check PIL and Pillow version numbers\r\nimport PIL\r\nprint('Pillow Version:', PIL.__version__)\r\nprint('PIL Version:', PIL.VERSION)<\/pre>\n<p>Running the example will print the version numbers for PIL and Pillow; your version numbers should be the same or higher.<\/p>\n<pre class=\"crayon-plain-tag\">Pillow Version: 5.3.0\r\nPIL Version: 1.1.7<\/pre>\n<p>Now that your environment is set up, let\u2019s look at how to load an image.<\/p>\n<h2>How to Load and Display Images<\/h2>\n<p>We need a test image to demonstrate some important features of using the Pillow library.<\/p>\n<p>In this tutorial, we will use a photograph of the <a href=\"https:\/\/www.flickr.com\/photos\/blachswan\/36102705716\/\">Sydney Opera House<\/a>, taken by Ed Dunens and made available on Flickr under a creative commons license, some rights reserved.<\/p>\n<div id=\"attachment_7344\" style=\"width: 650px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-7344\" class=\"size-full wp-image-7344\" src=\"https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2019\/01\/Sydney-Opera-House.jpg\" alt=\"Sydney Opera House\" width=\"640\" height=\"360\" srcset=\"http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Sydney-Opera-House.jpg 640w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Sydney-Opera-House-300x169.jpg 300w\" sizes=\"(max-width: 640px) 100vw, 640px\"><\/p>\n<p id=\"caption-attachment-7344\" class=\"wp-caption-text\">Sydney Opera House<\/p>\n<\/div>\n<ul>\n<li><a href=\"https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2019\/01\/Sydney-Opera-House.jpg\">Download Photo (opera_house.jpg)<\/a><\/li>\n<\/ul>\n<p>Download the photograph and save it in your current working directory with the file name \u201c<em>opera_house.jpg<\/em>\u201c.<\/p>\n<p>Images are typically in PNG or JPEG format and can be loaded directly using the <a href=\"https:\/\/pillow.readthedocs.io\/en\/stable\/reference\/Image.html#PIL.Image.Image\">open() function<\/a> on Image class. This returns an Image object that contains the pixel data for the image as well as details about the image. The Image class is the main workhorse for the Pillow library and provides a ton of properties about the image as well as functions that allow you to manipulate the pixels and format of the image.<\/p>\n<p>The \u2018<em>format<\/em>\u2018 property on the image will report the image format (e.g. JPEG), the \u2018<em>mode<\/em>\u2018 will report the pixel channel format (e.g. RGB or CMYK), and the \u2018<em>size<\/em>\u2018 will report the dimensions of the image in pixels (e.g. 640\u00d7480).<\/p>\n<p>The <em>show()<\/em> function will display the image using your operating systems default application.<\/p>\n<p>The example below demonstrates how to load and show an image using the Image class in the Pillow library.<\/p>\n<pre class=\"crayon-plain-tag\"># load and show an image with Pillow\r\nfrom PIL import Image\r\n# load the image\r\nimage = Image.open('opera_house.jpg')\r\n# summarize some details about the image\r\nprint(image.format)\r\nprint(image.mode)\r\nprint(image.size)\r\n# show the image\r\nimage.show()<\/pre>\n<p>Running the example will first load the image, report the format, mode, and size, then show the image on your desktop.<\/p>\n<pre class=\"crayon-plain-tag\">JPEG\r\nRGB\r\n(640, 360)<\/pre>\n<p>The image is shown using the default image preview application for your operating system, such as Preview on MacOS.<\/p>\n<div id=\"attachment_7345\" style=\"width: 1034px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-7345\" class=\"size-large wp-image-7345\" src=\"https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2019\/01\/Sydney-Opera-House-Displayed-Using-the-Default-Image-Preview-Application-1024x669.png\" alt=\"Sydney Opera House Displayed Using the Default Image Preview Application\" width=\"1024\" height=\"669\" srcset=\"http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Sydney-Opera-House-Displayed-Using-the-Default-Image-Preview-Application-1024x669.png 1024w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Sydney-Opera-House-Displayed-Using-the-Default-Image-Preview-Application-300x196.png 300w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Sydney-Opera-House-Displayed-Using-the-Default-Image-Preview-Application-768x502.png 768w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Sydney-Opera-House-Displayed-Using-the-Default-Image-Preview-Application.png 1276w\" sizes=\"(max-width: 1024px) 100vw, 1024px\"><\/p>\n<p id=\"caption-attachment-7345\" class=\"wp-caption-text\">Sydney Opera House Displayed Using the Default Image Preview Application<\/p>\n<\/div>\n<p>Now that you know how to load an image, let\u2019s look at how you can access the pixel data of images.<\/p>\n<h2>How to Convert Images to NumPy Arrays and Back<\/h2>\n<p>Often in machine learning, we want to work with images as NumPy arrays of pixel data.<\/p>\n<p>With Pillow installed, you can also use the Matplotlib library to load the image and display it within a Matplotlib frame.<\/p>\n<p>This can be achieved using the <a href=\"https:\/\/matplotlib.org\/api\/_as_gen\/matplotlib.pyplot.imread.html\">imread() function<\/a> that loads the image an array of pixels directly and the <a href=\"https:\/\/matplotlib.org\/api\/_as_gen\/matplotlib.pyplot.imshow.html\">imshow() function<\/a> that will display an array of pixels as an image.<\/p>\n<p>The example below loads and displays the same image using Matplotlib that, in turn, will use Pillow under the covers.<\/p>\n<pre class=\"crayon-plain-tag\"># load and display an image with Matplotlib\r\nfrom matplotlib import image\r\nfrom matplotlib import pyplot\r\n# load image as pixel array\r\ndata = image.imread('opera_house.jpg')\r\n# summarize shape of the pixel array\r\nprint(data.dtype)\r\nprint(data.shape)\r\n# display the array of pixels as an image\r\npyplot.imshow(data)\r\npyplot.show()<\/pre>\n<p>Running the example first loads the image and then reports the data type of the array, in this case, 8-bit unsigned integers, then reports the shape of the array, in this case, 360 pixels wide by 640 pixels high and three channels for red, green, and blue.<\/p>\n<pre class=\"crayon-plain-tag\">uint8\r\n(360, 640, 3)<\/pre>\n<p>Finally, the image is displayed using Matplotlib.<\/p>\n<div id=\"attachment_7346\" style=\"width: 1290px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-7346\" class=\"size-full wp-image-7346\" src=\"https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2019\/01\/Sydney-Opera-House-Displayed-Using-Matplotlib.jpg\" alt=\"Sydney Opera House Displayed Using Matplotlib\" width=\"1280\" height=\"960\" srcset=\"http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Sydney-Opera-House-Displayed-Using-Matplotlib.jpg 1280w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Sydney-Opera-House-Displayed-Using-Matplotlib-300x225.jpg 300w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Sydney-Opera-House-Displayed-Using-Matplotlib-768x576.jpg 768w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Sydney-Opera-House-Displayed-Using-Matplotlib-1024x768.jpg 1024w\" sizes=\"(max-width: 1280px) 100vw, 1280px\"><\/p>\n<p id=\"caption-attachment-7346\" class=\"wp-caption-text\">Sydney Opera House Displayed Using Matplotlib<\/p>\n<\/div>\n<p>The Matplotlib wrapper functions can be more effective than using Pillow directly.<\/p>\n<p>Nevertheless, you can access the pixel data from a Pillow Image. Perhaps the simplest way is to construct a NumPy array and pass in the Image object. The process can be reversed converting a given array of pixel data into a Pillow Image object using the <em>Image.fromarray()<\/em> function. This can be useful if image data is manipulated as a NumPy array and you then want to save it later as a PNG or JPEG file.<\/p>\n<p>The example below loads the photo as a Pillow Image object and converts it to a NumPy array, then converts it back to an Image object again.<\/p>\n<pre class=\"crayon-plain-tag\"># load image and convert to and from NumPy array\r\nfrom PIL import Image\r\nfrom numpy import asarray\r\n# load the image\r\nimage = Image.open('opera_house.jpg')\r\n# convert image to numpy array\r\ndata = asarray(image)\r\n# summarize shape\r\nprint(data.shape)\r\n# create Pillow image\r\nimage2 = Image.fromarray(data)\r\n# summarize image details\r\nprint(image2.format)\r\nprint(image2.mode)\r\nprint(image2.size)<\/pre>\n<p>Running the example first loads the photo as a Pillow image then converts it to a NumPy array and reports the shape of the array. Finally, the array is converted back into a Pillow image and the details are reported.<\/p>\n<pre class=\"crayon-plain-tag\">(360, 640, 3)\r\nJPEG\r\nRGB\r\n(640, 360)<\/pre>\n<p>Both approaches are effective for loading image data into NumPy arrays, although the Matplotlib <em>imread()<\/em> function uses fewer lines of code than loading and converting a Pillow Image object and may be preferred.<\/p>\n<p>For example, you could easily load all images in a directory as a list as follows:<\/p>\n<pre class=\"crayon-plain-tag\"># load all images in a directory\r\nfrom os import listdir\r\nfrom matplotlib import image\r\n# load all images in a directory\r\nloaded_images = list()\r\nfor filename in listdir('images'):\r\n\t# load image\r\n\timg_data = image.imread('images\/' + filename)\r\n\t# store loaded image\r\n\tloaded_images.append(img_data)\r\n\tprint('> loaded %s %s' % (filename, img_data.shape))<\/pre>\n<p>Now that we know how to load images as NumPy arrays, let\u2019s look at how to save images to file.<\/p>\n<h2>How to Save Images to File<\/h2>\n<p>An image object can be saved by calling the <em>save()<\/em> function.<\/p>\n<p>This can be useful if you want to save an image in a <a href=\"https:\/\/pillow.readthedocs.io\/en\/stable\/handbook\/image-file-formats.html\">different format<\/a>, in which case the \u2018<em>format<\/em>\u2018 argument can be specified, such as PNG, GIF, or PEG.<\/p>\n<p>For example, the code listing below loads the photograph in JPEG format and saves it in PNG format.<\/p>\n<pre class=\"crayon-plain-tag\"># example of saving an image in another format\r\nfrom PIL import Image\r\n# load the image\r\nimage = Image.open('opera_house.jpg')\r\n# save as PNG format\r\nimage.save('opera_house.png', format='PNG')\r\n# load the image again and inspect the format\r\nimage2 = Image.open('opera_house.png')\r\nprint(image2.format)<\/pre>\n<p>Running the example loads the JPEG image, saves it in PNG format, then loads the newly saved image again, and confirms that the format is indeed PNG.<\/p>\n<pre class=\"crayon-plain-tag\">PNG<\/pre>\n<p>Saving images is useful if you perform some data preparation on the image before modeling. One example is converting color images (RGB channels) to grayscale (1 channel).<\/p>\n<p>There are a number of ways to convert an image to grayscale, but Pillow provides the <em>convert()<\/em> function and the mode \u2018<em>L<\/em>\u2018 will convert an image to grayscale.<\/p>\n<pre class=\"crayon-plain-tag\"># example of saving a grayscale version of a loaded image\r\nfrom PIL import Image\r\n# load the image\r\nimage = Image.open('opera_house.jpg')\r\n# convert the image to grayscale\r\ngs_image = image.convert(mode='L')\r\n# save in jpeg format\r\ngs_image.save('opera_house_grayscale.jpg')\r\n# load the image again and show it\r\nimage2 = Image.open('opera_house_grayscale.jpg')\r\n# show the image\r\nimage2.show()<\/pre>\n<p>Running the example loads the photograph, converts it to grayscale, saves the image in a new file, then loads it again and shows it to confirm that the photo is now grayscale instead of color.<\/p>\n<div id=\"attachment_7347\" style=\"width: 1288px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-7347\" class=\"size-full wp-image-7347\" src=\"https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2019\/01\/Example-of-Grayscale-Version-of-Photograph.png\" alt=\"Example of Grayscale Version of Photograph\" width=\"1278\" height=\"832\" srcset=\"http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Example-of-Grayscale-Version-of-Photograph.png 1278w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Example-of-Grayscale-Version-of-Photograph-300x195.png 300w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Example-of-Grayscale-Version-of-Photograph-768x500.png 768w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Example-of-Grayscale-Version-of-Photograph-1024x667.png 1024w\" sizes=\"(max-width: 1278px) 100vw, 1278px\"><\/p>\n<p id=\"caption-attachment-7347\" class=\"wp-caption-text\">Example of Grayscale Version of Photograph<\/p>\n<\/div>\n<h2>How to Resize Images<\/h2>\n<p>It is important to be able to resize images before modeling.<\/p>\n<p>Sometimes it is desirable to thumbnail all images to have the same width or height. This can be achieved with Pillow using the <em>thumbnail()<\/em> function. The function takes a tuple with the width and height and the image will be resized so that the width and height of the image are equal or smaller than the specified shape.<\/p>\n<p>For example, the test photograph we have been working with has the width and height of (640, 360). We can resize it to (100, 100), in which case the largest dimension, in this case, the width, will be reduced to 100, and the height will be scaled in order to retain the aspect ratio of the image.<\/p>\n<p>The example below will load the photograph and create a smaller thumbnail with a width and height of 100 pixels.<\/p>\n<pre class=\"crayon-plain-tag\"># create a thumbnail of an image\r\nfrom PIL import Image\r\n# load the image\r\nimage = Image.open('opera_house.jpg')\r\n# report the size of the image\r\nprint(image.size)\r\n# create a thumbnail and preserve aspect ratio\r\nimage.thumbnail((100,100))\r\n# report the size of the thumbnail\r\nprint(image.size)<\/pre>\n<p>Running the example first loads the photograph and reports the width and height. The image is then resized, in this case, the width is reduced to 100 pixels and the height is reduced to 56 pixels, maintaining the aspect ratio of the original image.<\/p>\n<pre class=\"crayon-plain-tag\">(640, 360)\r\n(100, 56)<\/pre>\n<p>We may not want to preserve the aspect ratio, and instead, we may want to force the pixels into a new shape.<\/p>\n<p>This can be achieved using the <em>resize()<\/em> function that allows you to specify the width and height in pixels and the image will be reduced or stretched to fit the new shape.<\/p>\n<p>The example below demonstrates how to resize a new image and ignore the original aspect ratio.<\/p>\n<pre class=\"crayon-plain-tag\"># resize image and force a new shape\r\nfrom PIL import Image\r\n# load the image\r\nimage = Image.open('opera_house.jpg')\r\n# report the size of the image\r\nprint(image.size)\r\n# resize image and ignore original aspect ratio\r\nimg_resized = image.resize((200,200))\r\n# report the size of the thumbnail\r\nprint(img_resized.size)<\/pre>\n<p>Running the example loads the image, reports the shape of the image, then resizes it to have a width and height of 200 pixels.<\/p>\n<pre class=\"crayon-plain-tag\">(640, 360)\r\n(200, 200)<\/pre>\n<p>The sized of the image is shown and we can see that the wide photograph has been compressed into a square, although all of the features are still quite visible and obvious.<\/p>\n<p>Standard resampling algorithms are used to invent or remove pixels when resizing, and you can specify a technique, although default is a bicubic resampling algorithm that suits most general applications.<\/p>\n<div id=\"attachment_7348\" style=\"width: 1114px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-7348\" class=\"size-full wp-image-7348\" src=\"https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2019\/01\/Resized-Photograph-that-Does-Not-Preserve-the-Original-Aspect-Ratio.png\" alt=\"Resized Photograph That Does Not Preserve the Original Aspect Ratio\" width=\"1104\" height=\"550\" srcset=\"http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Resized-Photograph-that-Does-Not-Preserve-the-Original-Aspect-Ratio.png 1104w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Resized-Photograph-that-Does-Not-Preserve-the-Original-Aspect-Ratio-300x149.png 300w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Resized-Photograph-that-Does-Not-Preserve-the-Original-Aspect-Ratio-768x383.png 768w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Resized-Photograph-that-Does-Not-Preserve-the-Original-Aspect-Ratio-1024x510.png 1024w\" sizes=\"(max-width: 1104px) 100vw, 1104px\"><\/p>\n<p id=\"caption-attachment-7348\" class=\"wp-caption-text\">Resized Photograph That Does Not Preserve the Original Aspect Ratio<\/p>\n<\/div>\n<h2>How to Flip, Rotate, and Crop Images<\/h2>\n<p>Simple image manipulation can be used to create new versions of images that, in turn, can provide a richer training dataset when modeling.<\/p>\n<p>Generally, this is referred to as data augmentation and may involve creating flipped, rotated, cropped, or other modified versions of the original images with the hope that the algorithm will learn to extract the same features from the image data regardless of where they might appear.<\/p>\n<p>You may want to implement your own data augmentation schemes, in which case you need to know how to perform basic manipulations of your image data.<\/p>\n<h3>Flip Image<\/h3>\n<p>An image can be flipped by calling the <em>flip()<\/em> function and passing in a method such as <em>FLIP_LEFT_RIGHT<\/em> for a horizontal flip or <em>FLIP_TOP_BOTTOM<\/em> for a vertical flip. Other flips are also available<\/p>\n<p>The example below creates both horizontal and vertical flipped versions of the image.<\/p>\n<pre class=\"crayon-plain-tag\"># create flipped versions of an image\r\nfrom PIL import Image\r\nfrom matplotlib import pyplot\r\n# load image\r\nimage = Image.open('opera_house.jpg')\r\n# horizontal flip\r\nhoz_flip = image.transpose(Image.FLIP_LEFT_RIGHT)\r\n# vertical flip\r\nver_flip = image.transpose(Image.FLIP_TOP_BOTTOM)\r\n# plot all three images using matplotlib\r\npyplot.subplot(311)\r\npyplot.imshow(image)\r\npyplot.subplot(312)\r\npyplot.imshow(hoz_flip)\r\npyplot.subplot(313)\r\npyplot.imshow(ver_flip)\r\npyplot.show()<\/pre>\n<p>Running the example loads the photograph and creates horizontal and vertical flipped versions of the photograph, then plots all three versions as subplots using Matplotlib.<\/p>\n<p>You will note that the <em>imshow()<\/em> function can plot the Image object directly without having to convert it to a NumPy array.<\/p>\n<div id=\"attachment_7349\" style=\"width: 1290px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-7349\" class=\"size-full wp-image-7349\" src=\"https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2019\/01\/Plot-of-Original-Horizontal-and-Vertical-Flipped-Versions-of-a-Photograph.png\" alt=\"Plot of Original, Horizontal, and Vertical Flipped Versions of a Photograph\" width=\"1280\" height=\"960\" srcset=\"http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Plot-of-Original-Horizontal-and-Vertical-Flipped-Versions-of-a-Photograph.png 1280w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Plot-of-Original-Horizontal-and-Vertical-Flipped-Versions-of-a-Photograph-300x225.png 300w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Plot-of-Original-Horizontal-and-Vertical-Flipped-Versions-of-a-Photograph-768x576.png 768w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Plot-of-Original-Horizontal-and-Vertical-Flipped-Versions-of-a-Photograph-1024x768.png 1024w\" sizes=\"(max-width: 1280px) 100vw, 1280px\"><\/p>\n<p id=\"caption-attachment-7349\" class=\"wp-caption-text\">Plot of Original, Horizontal, and Vertical Flipped Versions of a Photograph<\/p>\n<\/div>\n<h3>Rotate Image<\/h3>\n<p>An image can be rotated using the <em>rotate()<\/em> function and passing in the angle for the rotation.<\/p>\n<p>The function offers additional control such as whether or not to expand the dimensions of the image to fit the rotated pixel values (default is to clip to the same size), where to center the rotation the image (default is the center), and the fill color for pixels outside of the image (default is black).<\/p>\n<p>The example below creates a few rotated versions of the image.<\/p>\n<pre class=\"crayon-plain-tag\"># create rotated versions of an image\r\nfrom PIL import Image\r\nfrom matplotlib import pyplot\r\n# load image\r\nimage = Image.open('opera_house.jpg')\r\n# plot original image\r\npyplot.subplot(311)\r\npyplot.imshow(image)\r\n# rotate 45 degrees\r\npyplot.subplot(312)\r\npyplot.imshow(image.rotate(45))\r\n# rotate 90 degrees\r\npyplot.subplot(313)\r\npyplot.imshow(image.rotate(90))\r\npyplot.show()<\/pre>\n<p>Running the example plots the original photograph, then a version of the photograph rotated 45 degrees, and another rotated 90 degrees.<\/p>\n<p>You can see that in both rotations, the pixels are clipped to the original dimensions of the image and that the empty pixels are filled with black color.<\/p>\n<div id=\"attachment_7350\" style=\"width: 1290px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-7350\" class=\"size-full wp-image-7350\" src=\"https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2019\/01\/Plot-of-Original-and-Rotated-Version-of-a-Photograph.png\" alt=\"Plot of Original and Rotated Version of a Photograph\" width=\"1280\" height=\"960\" srcset=\"http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Plot-of-Original-and-Rotated-Version-of-a-Photograph.png 1280w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Plot-of-Original-and-Rotated-Version-of-a-Photograph-300x225.png 300w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Plot-of-Original-and-Rotated-Version-of-a-Photograph-768x576.png 768w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Plot-of-Original-and-Rotated-Version-of-a-Photograph-1024x768.png 1024w\" sizes=\"(max-width: 1280px) 100vw, 1280px\"><\/p>\n<p id=\"caption-attachment-7350\" class=\"wp-caption-text\">Plot of Original and Rotated Version of a Photograph<\/p>\n<\/div>\n<h3>Cropped Image<\/h3>\n<p>An image can be cropped: that is, a piece can be cut out to create a new image, using the <em>crop()<\/em> function.<\/p>\n<p>The crop function takes a tuple argument that defines the two x\/y coordinates of the box to crop out of the image. For example, if the image is 2,000 by 2,000 pixels, we can clip out a 100 by 100 box in the middle of the image by defining a tuple with the top-left and bottom-right points of (950, 950, 1050, 1050).<\/p>\n<p>The example below demonstrates how to create a new image as a crop from a loaded image.<\/p>\n<pre class=\"crayon-plain-tag\"># example of cropping an image\r\nfrom PIL import Image\r\n# load image\r\nimage = Image.open('opera_house.jpg')\r\n# create a cropped image\r\ncropped = image.crop((100, 100, 200, 200))\r\n# show cropped image\r\ncropped.show()<\/pre>\n<p>Running the example creates a cropped square image of 100 pixels starting at 100,100 and extending down and left to 200,200. The cropped square is then displayed.<\/p>\n<div id=\"attachment_7351\" style=\"width: 1104px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-7351\" class=\"size-full wp-image-7351\" src=\"https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2019\/01\/Example-of-a-Cropped-Version-of-a-Photograph.png\" alt=\"Example of a Cropped Version of a Photograph\" width=\"1094\" height=\"554\" srcset=\"http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Example-of-a-Cropped-Version-of-a-Photograph.png 1094w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Example-of-a-Cropped-Version-of-a-Photograph-300x152.png 300w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Example-of-a-Cropped-Version-of-a-Photograph-768x389.png 768w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/01\/Example-of-a-Cropped-Version-of-a-Photograph-1024x519.png 1024w\" sizes=\"(max-width: 1094px) 100vw, 1094px\"><\/p>\n<p id=\"caption-attachment-7351\" class=\"wp-caption-text\">Example of a Cropped Version of a Photograph<\/p>\n<\/div>\n<h2>Extensions<\/h2>\n<p>This section lists some ideas for extending the tutorial that you may wish to explore.<\/p>\n<ul>\n<li><strong>Your Own Images<\/strong>. Experiment with Pillow functions for reading and manipulating images with your own image data.<\/li>\n<li><strong>More Transforms<\/strong>. Review the Pillow API documentation and experiment with additional image manipulation functions.<\/li>\n<li><strong>Image Pre-processing<\/strong>. Write a function to create augmented versions of an image ready for use with a deep learning neural network.<\/li>\n<\/ul>\n<p>If you explore any of these extensions, I\u2019d love to know.<\/p>\n<h2>Further Reading<\/h2>\n<p>This section provides more resources on the topic if you are looking to go deeper.<\/p>\n<ul>\n<li><a href=\"https:\/\/python-pillow.org\/\">Pillow Homepage<\/a><\/li>\n<li><a href=\"https:\/\/pillow.readthedocs.io\/en\/stable\/installation.html\">Pillow Installation Instructions<\/a><\/li>\n<li><a href=\"https:\/\/pillow.readthedocs.io\/en\/5.3.x\/\">Pillow (PIL Fork) API Documentation<\/a><\/li>\n<li><a href=\"https:\/\/pillow.readthedocs.io\/en\/stable\/handbook\/tutorial.html\">Pillow Handbook Tutorial<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/python-pillow\/Pillow\">Pillow GitHub Project<\/a><\/li>\n<li><a href=\"http:\/\/www.pythonware.com\/products\/pil\/\">Python Imaging Library (PIL) Homepage<\/a><\/li>\n<li><a href=\"https:\/\/en.wikipedia.org\/wiki\/Python_Imaging_Library\">Python Imaging Library, Wikipedia.<\/a><\/li>\n<li><a href=\"https:\/\/matplotlib.org\/users\/image_tutorial.html\">Matplotlib: Image tutorial<\/a><\/li>\n<\/ul>\n<h2>Summary<\/h2>\n<p>In this tutorial, you discovered how to load and manipulate image data using the Pillow Python library.<\/p>\n<p>Specifically, you learned:<\/p>\n<ul>\n<li>How to install the Pillow library and confirm it is working correctly.<\/li>\n<li>How to load images from file, convert loaded images to NumPy arrays, and save images in new formats.<\/li>\n<li>How to perform basic transforms to image data such as resize, flips, rotations, and cropping.<\/li>\n<\/ul>\n<p>Do you have any questions?<br \/>\nAsk your questions in the comments below and I will do my best to answer.<\/p>\n<p>The post <a rel=\"nofollow\" href=\"https:\/\/machinelearningmastery.com\/how-to-load-and-manipulate-images-for-deep-learning-in-python-with-pil-pillow\/\">How to Load and Manipulate Images for Deep Learning in Python With PIL\/Pillow<\/a> appeared first on <a rel=\"nofollow\" href=\"https:\/\/machinelearningmastery.com\/\">Machine Learning Mastery<\/a>.<\/p>\n<\/div>\n<p><a href=\"https:\/\/machinelearningmastery.com\/how-to-load-and-manipulate-images-for-deep-learning-in-python-with-pil-pillow\/\">Go to Source<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Author: Jason Brownlee Before you can develop predictive models for image data, you must learn how to load and manipulate images and photographs. The most [&hellip;] <span class=\"read-more-link\"><a class=\"read-more\" href=\"https:\/\/www.aiproblog.com\/index.php\/2019\/03\/21\/how-to-load-and-manipulate-images-for-deep-learning-in-python-with-pil-pillow\/\">Read More<\/a><\/span><\/p>\n","protected":false},"author":1,"featured_media":1906,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_bbp_topic_count":0,"_bbp_reply_count":0,"_bbp_total_topic_count":0,"_bbp_total_reply_count":0,"_bbp_voice_count":0,"_bbp_anonymous_reply_count":0,"_bbp_topic_count_hidden":0,"_bbp_reply_count_hidden":0,"_bbp_forum_subforum_count":0,"footnotes":""},"categories":[24],"tags":[],"_links":{"self":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/posts\/1905"}],"collection":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/comments?post=1905"}],"version-history":[{"count":0,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/posts\/1905\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/media\/1906"}],"wp:attachment":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/media?parent=1905"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/categories?post=1905"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/tags?post=1905"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}