- How to Display and Convert Images in Python
- Loading and Displaying an Image in Python
- Showing Image Properties Using Python
- Saving an Image
- Summary
- Displaying Images in Python
- Pillow supported image formats
- 2. Display images in python with OpenCV
- 3. IPython library to Display images in python
- 4. Matplot library to Display images in python
- 5. Tkinter GUI to Display images in python
- Tkinter supported image formats
- 6. Tkinter and Pillow library to a Display JPEG image in python
- 7. Scikit-image library to a Display JPEG image in python
- Conclusion
How to Display and Convert Images in Python
Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.
Python is gaining more attention and attraction than most other programming languages today. It’s gained that popularity for a variety of reasons. It is both object-oriented and procedural, it’s open-sourced and extensible, it’s portable, and it has library support. Most importantly, however, is that Python is simple to code and very readable.
To illustrate how easy some things are to do in Python, we’ll take a quick look at working with images. We’ll show how to load and display an image using Python, how to get image information using Python, and how to convert image formats using Python.
Of course, to use images in Python, you need to have Python installed. Additionally, you will want to make sure you have the Pillow module installed. Installing the Pillow module can be done using the simple command line directive of:
This will install an updated version of the Python Image Library (PIL), which will allow you to load and use images. Once you’ve installed Pillow, you are ready to start working with images.
Loading and Displaying an Image in Python
Writing an application to display an image in Python can be done with just a couple of lines of code as shown in Listing 1:
Listing 1: Img.py: Loading an Image in Python
from PIL import Image image = Image.open('image.jpg') image.show()
The code in listing 1 starts by importing the Image library. With the library loaded, you can load an image by call in the Image.open() method and assign the return value to a variable. With the image loaded, you are ready to display the image by calling the show() method on your image variable. If you run Listing 1 in a directory that contains an image named image.jpg, the image will be displayed. The following shows the image being displayed on a Windows system:
Showing Image Properties Using Python
In addition to showing an image, the Image class provides a number of other properties and methods that can be used with images. Some of the key properties include:
- filename: The name of the image file
- format: The file format such as JPG, GIF
- mode: The image mode such as RGB, RFBA, CMYK, or YCbCr
- size: The image size in pixels displayed as a width, height tuple
- width: The width of the image in pixels
- height: The height of the image in pixels
- is_animated: Indicates if the image is more than one frame. True if it is, False if it is not. This attribute is not included in all images.
Listing 2 shows how simple it is to load an image called “ani.gif” and display a bunch of its attributes. The image is included in this article just before the code:
Listing 2: Img.py – Displaying Image Attributes Using Python
from PIL import Image image = Image.open('ani.gif') print("Filename: ", image.filename) print("Format: ", image.format) print("Mode: ", image.mode) print("Size: ", image.size) print("Width: ", image.width) print("Height: ", image.height) print("Is Animated: ", (getattr(image, "is_animated", False))) image.close() # close image file
It is worth noting that the ani.gif image is an animated gif, so when this listing is executed, the following information is displayed:
You can see that the animated gif is 500 by 500 pixels, it is indeed a GIF, and it is animated. In addition to the properties shown in Listing 2, there are two others you can check.
The first of these properties is palette. This is the color palette table if one is included with the image. The value is None if there is not a palette. For the ani.gif shown above, the color palette information that is shown when calling the property is:
For the original jpg image used in Listing 1, the palette information was None.
The final property is info. Info is a dictionary object that allows for various non-image information to be shared.
Saving an Image
Opening an image was as simple as calling the open() method. Saving an image in Python is just as simple. You simply call save() and pass in the name you want used to save your image. This method will save the image in the format identified by the extension on the filename you pass in. Listing 3 opens the image.jpg file used in Listing 1 and saves it as a gif file by changing the filename that is passed to save().
Listing 3: Saving a File in Python
from PIL import Image image = Image.open('image.jpg') image.save("NewImage.gif")
The save() method can receive a file object instead of a filename. It also can have two additional parameters passed that specifies the format you want used to save the file. The formats include BMP, DIB, EPS, GIF, ICO, JPEG, PCX, PNG, TIFF, and a multitude of others. The format would be specified as the second parameter as such:
image.save("NewImage", format="BMP")
Summary
This was a relatively short article because it is relatively easy to work with images in Python! You learned how to open an image in Python. You also saw how to obtain information about the image and how to then save a copy of the image in a different format. In the next article, you’ll see a few ways to manipulate an image once you’ve loaded it. Again, with the use of Python, you’ll find the manipulation comes easy!
Displaying Images in Python
Pillow is a powerful imaging library of Python language that helps to display images with editing capabilities. It is the fastest method to process and display images as compared to other imaging libraries. It temporarily stores images in a default program folder and displays that as an output in a standard program such as store image temporarily and display in Window’s Photo program instead of displaying it in a separate output window. Once Execution is finished to display the image in a standard file, the temporarily stored files are deleted from the default program that is used to display the image.
Pillow supported image formats
It supports more than thirty image formats. some popular formats are JPEG, BMP, PNG, PPM, TIFF, and GIF.
- import image and image class from Pillow library.
- open an image from files by specifying its path
- display in the default program.
#Display Images using PIL library # Import Image class from PIL package from PIL import Image # Load image from file img = Image.open(r"C:\Users\aisha\Desktop\lake.jpg") img.show()
2. Display images in python with OpenCV
OpenCV is a real-time computer vision library that works on the processing of an image or a video to identify the objects from them. It supports all formats of images. cv2.imshow() command displays the image in a separate window that is fit to the image size.
OpenCV supported image formats
BMP, dib, JPEG files, png, ppm, ppm, sr, ras, tiff
Note: It read image and convert into greyscale if flag value is 0 and change to the colorful image if specified flag value increase.
OpenCV does not display images and responds to an empty window in case of the file is missing or following invalid formats etc.
Install OpenCV in your active environment if it is not pre-installed.
- Import the latest module of OpenCV that is cv2
- Load an image from specifying path and load image as a grayscale image by assigning the value 0
- Display image with im.show()
#Display Images using OpenCV import cv2 # Load a color image in grayscale img = cv2.imread(r'C:\Users\aisha\Desktop\lake.jpg', 0) cv2.imshow(r'C:\Users\aisha\Desktop\lake.jpg', img)
Output when flag value is 0.
#Display Images using OpenCV library import cv2 # Load an image img = cv2.imread(r'C:\Users\aisha\Desktop\lake.jpg') cv2.imshow(r'C:\Users\aisha\Desktop\lake.jpg', img)
Output when flag value is default
3. IPython library to Display images in python
If you are using Jupyter notebook for python programming, this library helps to display the image below your code in the notebook.
- Import display from IPython library that will display image.
- Show an image that the path is specified in the display command.
#Display Images using IPyton library from IPython import display display.Image(r"C:\Users\aisha\Desktop\lakeimage.png")
4. Matplot library to Display images in python
Matplot is a visualization library, based on NumPy arrays to visualize the data in 2D plots.
- import plt and mpimg packages that help to manipulate images.
- load and read an image by imread command.
- Display output image with number axes. ####Matplot supported image formats ps, eps, pdf, png, raw, rgba, svg, svgz, jpg, jpeg, tif, and tiff. Note: you can turn off the number axes by using the plt.axis(«off») command.
#Display Images using Matplot library import matplotlib.pyplot as plt import matplotlib.image as mpimg img = mpimg.imread(r'C:\Users\aisha\Desktop\lake.jpg') imgplot = plt.imshow(img) plt.show()
5. Tkinter GUI to Display images in python
Tkinter toolkit is the easiest and fastest method to build graphical Interface applications in python. It helps to create a GUI application within few lines of code.
tkinter opens only the image size that is assigned in the geometry command.
Tkinter supported image formats
- Import tkinter module (Note: use tkinter for 3.x python version and Tkinter for less than 3.x python versions)
- m is the name of an object of the output window. It creates a parent window
- set the size of the window in which you want to display the image.
- read the image as an input and store it in the photo variable.
- create a label that stores the image. It is the child of m widget.
- pack that label that works as a container box.
- use main loop() to run the program infinite times until the output window closed *Note: Below program only displays PNG, PPM, and GIF. It does not support JPEG format images. *
#Display Images using tkinter GUI from tkinter import * m = Tk() m.geometry("700x500") photo = PhotoImage(file= r"C:\Users\aisha\Desktop\lakeimage.png") img_label = Label(image=photo) img_label.pack() m.mainloop()
6. Tkinter and Pillow library to a Display JPEG image in python
To display JPEG images in Tkinter, We also use the PIL library because it supports more than 30 formats.
from tkinter import * from PIL import Image, ImageTk m = Tk() m.geometry("900x500") image= Image.open(r"C:\Users\aisha\Desktop\lake.jpeg ") photo = ImageTk.PhotoImage(image) img_label = Label(image=photo) img_label.pack() m.mainloop()
7. Scikit-image library to a Display JPEG image in python
Scikit is a python distributed module for Scipy that is developed independently. It is an open-source Scipy toolkit, contains many image processing algorithms such as geometry, morphology, segmentation, filtration, etc.
Note: Scikit and Skimag are the same package.
Scikit supported image formats
Scikit works with the NumPy array that supports many data types within a particular range. This method display image with axes values. Its output is the same as the output by using matplot with pyplot package.
- Before running the scikit-image library, first install NumPy, SciPy, and Scikit-image to your python active environment.
- Import image libraries from the skimage package.
- load the file from the specified path.
- Read the file as an input.
- Display the file as output by using io.
#Display Images using scikit-image import os # Importing io from skimage import skimage from skimage import io # Load lake image from file file = os.path.join(skimage.data_dir, r"C:\Users\aisha\Desktop\lake.jpg" ) lake = io.imread(file) # Show the input image io.imshow(lake) io.show()
Conclusion
Displaying images in python is not a difficult task. In this article, we use six different libraries and packages of python to display image. We use Pillow, Matplot, Tkinter, Scikit, OpenCV, and IPython libraries to display images.