How to save image in python

6 Ways to Save image to file in Python

In this Python tutorial, we will learn how to save an image to file in python.

Saving an image to a file in Python can be done using various methods. Here are some of the most common ways to save an image in Python:

  • Using the OpenCV library
  • Using the PIL library
  • Using the URLLIB library
  • Using the matplotlib library
  • Using the pickle module
  • Using the skimage library

How to Python save an image to file

Let us see in detail the above 6 ways to save an image to a file in Python.

Читайте также:  Закрыть часть кода php

Method-1: Python save an image to file using OpenCV library

OpenCV is a popular computer vision library that provides a function cv2.imwrite() to save an image to a file in Python.

# Import the necessary libraries import cv2 import os # Set the file path for the source image path = r'C:\Users\Administrator.SHAREPOINTSKY\Downloads\dora.jpg' # Set the directory for saving the image directory = r'C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work' # Load the image using OpenCV img = cv2.imread(path) # Change the working directory to the specified directory for saving the image os.chdir(directory) # Print the list of files in the directory before saving the image print("Before saving") print(os.listdir(directory)) # Save the image with the filename "cat.jpg" filename = 'cat.jpg' cv2.imwrite(filename, img) # Print the list of files in the directory after saving the image print("After saving") print(os.listdir(directory)) 

The above code uses the OpenCV and OS libraries in Python to perform the following tasks:

  • Imports the required libraries: cv2 and os.
  • Sets the file path for the source image to path, which is a string representing the file location on the local system.
  • Sets the directory for saving the image to directory, which is a string representing the directory location on the local system.
  • Loads the image using the cv2.imread() function and stores it in the variable img .
  • Changes the current working directory to the specified directory for saving the image using the os.chdir() function.
  • Prints the list of files in the directory before saving the image using the os.listdir() function and print() statement.
  • Saves the image to the specified directory with the filename cat.jpg using the cv2.imwrite() function.
  • Prints the list of files in the directory after saving the image using the os.listdir() function and print() statement.
Читайте также:  Мультиклассы

Here, we can the list of directories before and after saving as the output. You can refer to the below screenshot for the output.

Python save the file with OpenCV2

Method-2: Python save an image to file using the PIL library

PIL (Python Imaging Library) is another popular library for image manipulation in Python. It provides a method Image.save() to save an image to a file.

# Import the Image module from the PIL library from PIL import Image import PIL # Open the image with the specified file path picture = Image.open(r'Downloads\3.jpg') # Save the image with the specified file name picture = picture.save("dolls.jpg") 

The above code uses the Python Imaging Library (PIL) to perform the following tasks:

  • Imports the Image module from the PIL library using the from PIL import Image statement.
  • Imports the PIL library using the import PIL statement.
  • Opens an image with the specified file path using the Image.open() function and stores it in the picture variable.
  • Saves the image with the specified filename dolls.jpg using the .save() method. The .save() method is a method of the Image class and is used to save the image to disk. The method updates the picture variable with the saved image.

How to save an image using a pillow in python

Method-3: Python save an image to file using the matplotlib library

Matplotlib is a plotting library in Python that provides a function savefig() to save a figure to a file. To save an image, you can first plot it using Matplotlib and then save it using the savefig() function.

# Import the matplotlib.pyplot library as plt import matplotlib.pyplot as plt # Read the image file img = plt.imread("https://i0.wp.com/pythonguides.com/content/simon-berger.jpg") # Display the image plt.imshow(img) # Save the image plt.savefig("saved_image.jpg") 

The above code uses the matplotlib library to perform the following tasks:

  • Imports the Matplotlib’s Pyplot module using the import matplotlib.pyplot as plt statement.
  • Reads the image file with the specified file path using the plt.imread() function and stores it in the img variable.
  • Displays the image using the plt.imshow() function.
  • Saves the image to disk with the specified file name saved_image.jpg using the plt.savefig() function.

Python save an image to file using the matplotlib

Method-4: Python save an image to file using the URLLIB library

Another way to save an image to a file in Python is by using the urllib library. The urllib library provides a function urlretrieve() that can be used to download an image from a URL and save it to a file.

# Import the urllib and PIL libraries import urllib.request from PIL import Image import PIL # Retrieve the image from the specified URL and print the result print(urllib.request.urlretrieve("https://bit.ly/3oAeohK")) # Open the image with the specified file name image = PIL.Image.open("new.png") # Show the image image.show() 

The above code uses the urllib and Python Imaging Library (PIL) to perform the following tasks:

  1. Imports the urllib and PIL libraries using the import urllib.request and from PIL import Image statements.
  2. Retrieves the image from the specified URL using the urllib.request.urlretrieve() function and stores the result in the new.png file.
  3. Opens the image with the specified file name new.png using the PIL.Image.open() function and stores it in the image variable.
  4. Displays the image using the image.show() function.

The URL is saved in the image format as the output in the below screenshot.

Python save an image to file from URL

Method-5: Python save an image to file using the pickle module

The pickle module in Python can also be used to save an image to a file. Pickle is a module that allows you to serialize and deserialize Python objects, including images.

# Import the pickle and matplotlib.pyplot modules import pickle import matplotlib.pyplot as plt # Read the image file with the specified file path img = plt.imread("https://i0.wp.com/pythonguides.com/content/saved_image.jpg") # Open the file with write binary mode to store the image using pickle with open("saved_image.pickle", "wb") as f: # Dump the image data into the file using pickle pickle.dump(img, f) 

The above code performs the following tasks:

  • Imports the pickle and matplotlib.pyplot modules.
  • Reads an image file with the specified file path /content/saved_image.jpg using the plt.imread() function and stores the image data in the img variable.
  • Opens a file with the specified name saved_image.pickle in write binary mode using the with open(“saved_image.pickle”, “wb”) as f: statement.
  • Dumps the image data stored in the img variable into the opened file using the pickle.dump(img, f) statement. This process serializes the image data into binary form and writes it to the file, allowing it to be stored and retrieved later.

Python save an image to file using the pickle

Method-6: Python save an image to file using the skimage library

Scikit-image is a library for image processing in Python that provides a function imsave() to save an image to a file.

# Import the imsave and imread functions from the skimage.io module from skimage.io import imsave, imread # Read the image file with the specified file path img = imread("https://i0.wp.com/pythonguides.com/content/simon-berger.jpg") # Save the image to disk with the specified file name imsave("saved_image.jpg", img)

The above code uses the skimage library to perform the following tasks:

  1. Imports the imsave and imread functions from the skimage.io module using the from skimage.io import imsave, imread statement.
  2. Reads the image file with the specified file path /content/simon-berger.jpg using the imread() function and stores it in the img variable.
  3. Saves the image to disk with the specified file name saved_image.jpg using the imsave() function. The img variable is passed as the image data to be saved.

Python save an image to file using the skimage

You may also like to read the following Python tutorials.

In this tutorial, we have learned about how to save an image to file in python, and also we have covered these methods:

  • Using the OpenCV library
  • Using the PIL library
  • Using the URLLIB
  • Using the matplotlib library
  • Using the pickle
  • Using the skimage library

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

How to open, show and save images in PIL (pillow) – with Python Examples

Python PIL (pillow) library can be used for advanced image processing needs but you will still need to cover the basics about handling images.

In this Python tutorial, we’re going to show you how to open, show and save an image using PIL (pillow) library in Python.

To work with images in PIL you need to first import the Image module from the PIL library in Python.

Holy Python is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

.open() method from PIL’s Image module

To open an image in PIL .open() method can be used.

If you encounter an error with the path to your image because there can be operating system conflicts especially regarding directory representation.

In most cases it helps to type the file path in raw string format or use backslashes instead of regular slashes.

At this point your image will be assigned to img variable but nothing will happen until you use the .show method as below.

.show() method from PIL’s Image module

Once you opened an image you can show it using the .show method.

.save() method from PIL’s Image module

After you worked on an image, do some image processing or image manipulation you will likely want to save this new version of your image.

Saving an image can be achieved by using .save() method with PIL library’s Image module in Python.

Example 1: How to open an image with PIL

To open an image in PIL you need to first import the Image module from the PIL library in Python.

from PIL import Image file = "C://Users/ABC/Motorbike.jpg" img = Image.open(file) 

Example 2: How to show an image with PIL

from PIL import Image file = "C://Users/ABC/Motorbike.jpg" img = Image.open(file) img.show() 

Example 3: How to save an image with PIL

from PIL import Image file = "C://Users/ABC/Motorbike.jpg" img = Image.open(file) img.save(Desktop/new_img.jpg) 

Tip 1: PIL is smart about opening images

PIL imaging library is pretty smart. Although it might not be ideal in all cases you can open files without even typing their full name or file extensions.

PIL library’s Image module will forgive such mistakes while opening files and figure out the file extension of the image by itself.

from PIL import Image file = "C://Users/ABC/Motorbike" img = Image.open(file) 

Tip 2: Incorporate try / except statements in your code

It’s common to work with multiple images during image processing as it can be very convenient.

When you have a loop or algorithm to go through hundreds or thousands of images, mistakes can happen.

If you use try / except statements your code will run uninterrupted despite individual errors.

You can read more about the correct usage on our try / except statements Python tutorial and common Python Errors tutorial.

from PIL import Image folder_path = "C://Users/ABC/Images123" for i in folder_path: try: img = Image.open(i) except Exception: pass

Resources

If you’d like to see more interesting content regarding image processing in Python you may want to check out our more advanced Python PIL tutorials as well as Digital Imaging basics below:

Summary

In this Python Tutorial, we’ve seen how to open, show and save images in Python using PIL library’s Image module.

We have demonstrated these topics with Python code examples and we have also shared a couple of useful and interesting Python tips that can help you become a more advanced Python coder.

Источник

Оцените статью