Convert image to grayscale in python

Convert image to grayscale in Python

A grayscale image is an image that simply contains only the shades of gray and no other color. The main advantage of using a grayscale image over a colored image is that it brings down the computational requirements, increases the speed of processing, and makes a significant impact on the complexity of the algorithm.

This tutorial discusses the different ways available to convert image to grayscale in Python.

Using the .convert() function from the Pillow Imaging Library (Fork) to convert image to grayscale in Python.

The Pillow Imaging Library is an open-source additional library that can be added to Python and is utilized for providing the functions that help in the opening, saving, and manipulating different image file formats in Python. This library is available on all Windows, Linux, and MacOS X.

The .convert() function takes an image as its parameter and is utilized to convert the given image into an image type that the user specifies in its mode parameter.

The .convert() function provides different modes for the process of conversion of an image to grayscale in Python. Below are the modes that are usable for this process.

  • 1 : It can be defined as a true black and white image mode that only has a 1-bit channel and takes only two values, either full black or full white.
  • L : It is an abbreviation for Luminance Channel. It is an 8-bit B&W/grayscale image mode. It usually takes up any value in the range of 0 to 255, which represents all the colors that are white, black with all the shades of gray in between them.
  • LA : An abbreviation for Luminance with Alpha Transparency Channel. It is utilized when the converted image needs to be successfully converted with transparency. This mode only provides support for images with the .png and the .gif file extensions.

The following code uses the .convert() function from the Pillow Imaging Library (Fork) to convert image to grayscale in Python.

Explanation
  • The original image is opened and stored as orig in the Python code using the Image.open() function.
  • The image is converted to grayscale and stored in the variable gsi. In this code, we use the 8-bit L mode.
  • Finally, the picture stored in the variable gsi is saved and stored on to the system.

The above code converts a colored image into a grayscale image. Here is a comparison between both the pictures.

Original Image :

Converted Image (After grayscale):

Using the OpenCV library functions to convert image to grayscale in Python.

Another method to convert an image to grayscale is with the use of several functions from the OpenCV library. OpenCV is an enormous library that provides functions that are used for Machine learning, Computer Vision, and Image Processing. It is supported not only by Python but also other languages like Java, C++, etc.

OpenCV provides several functions for image processing which are used here to convert the given image to grayscale. The module is not in-built and needs to be imported to the Python code to successfully run the code without any errors.

The following code uses the OpenCV library functions to convert image to grayscale in Python.

The output of the code would be the same as that of the method mentioned in the article above.

Explanation
  • The OpenCV module or cv2 is imported to the Python code first.
  • The original image is first loaded to the program code using the imread() function.
  • The loaded image is then converted to grayscale with the help of the .cvtColor() function.
  • The converted file is then stored on the disk with the help of the imwrite() function.

Using the color.rgb2gray() function from the scikit-image module to convert image to grayscale in Python.

scikit-image is an open-source and free-to-use library that provides various functions only for the purpose of image processing in Python. The color and io sub-modules from the skimage module need to be imported to the Python code in order to use the color.rgb2gray() function.

The color.rgb2gray() function is utilized to take an image in the RGB format as an argument and return a grayscale copy of the original image.

The following code uses the color.rgb2gray() function from the scikit-image module to convert image to grayscale in Python.

The output of the above code would be the same as the other codes mentioned above in the article.

Explanation
  • color and io are imported from the skimage module to run the code without any errors.
  • The io.imread() function is utilized to load the original image to the Python code.
  • The color.rgb2gray() function takes in the original image and returns a grayscale image to the Python code, which is stored in the variable gsi.

Using the Conversion Formula along with the matplotlib library to convert image to grayscale in Python.

There exists a standard conversion formula for converting images in RGB format to grayscale directly. The determined formula for this is gsi = 0.2989 * R + 0.5870 * G + 0.1140 * B.

Along with the standard conversion formula, we also need to use and import the matplotlib library in order to successfully implement this method.

Matplotlib is a cross-platform library that is mainly used for graphical plotting and data visualization in Python and the NumPy library which is an extension of Python.

The following code uses the Conversion Formula along with the matplotlib library to convert image to grayscale in Python.

The output of the above code would be the same as the other codes mentioned above in the article.

Explanation
  • The matplotlib module is imported to the Python code to successfully run the code without any errors in Python.
  • The image is loaded to the code using the mpimg.read() function.
  • Then, the dimension matrices of the RGB image are taken.
  • Then, the given conversion formula is applied to the dimension matrices in order to convert the image to grayscale.
  • The converted image is then stored and shown using the plt.imshow() function.

That’s all about how to convert image to grayscale in Python.


import_contacts

You may also like:

Related Posts

  • Python get year from date
    23 January

    Get year from Date in Python

    Table of ContentsDates in PythonWays to get year from date stored in a datetime object in PythonUsing the year attributeUsing the strftime() functionUsing the pandas.to_datetime functionWays to get year from date stored as a string in PythonUsing the for loopUsing the re.search()Conclusion In this post, we will see how to get year from Date in […]

  • 22 January

    Replace space with underscore in Python

    Table of ContentsWays to replace space with underscore in PythonUsing the for loopUsing the replace() functionUsing the re.sub() functionUsing the split() and join() functionConclusion Strings are an essential data type in programming. In Python, we can treat strings as an iterable of characters, and can perform a variety of functions and operations on them. Replacing […]

  • Python copy file to another directory
    17 January

    How to copy file to another directory in Python

    Table of ContentsWays to copy file to another directoy in PythonUsing file handlingUsing the shutil libraryUsing the pathlib libraryUsing the os moduleUsing the subprocess moduleConclusion In this article, we will see different ways to copy file to another directory in Python. We can read and write files in Python. We can also work with paths […]

  • Check if variable is String in Python
    13 January

    Check if variable is String in python

    Table of ContentsHow to check if a given variable is of the string type in Python?Using the isinstance() function.Using the type() function.Check if function parameter is String In this post, we will see what is a string in Python and how to check whether a given variable is a string or not. There are many […]

  • Count the number of characters in a String in Python
    13 January

    Count number of characters in a string in python

    Table of ContentsWays to count the number of characters in a string in PythonUsing the len() functionUsing the for loopUsing the collections.Counter classConclusion In this post, we will see how to count number of characters in a String in Python. We can think of strings as a collection of characters, with every character at a […]

  • Pandas apply function to column
    12 January

    Pandas apply function to column

    Table of ContentsHow do I apply function to column in pandas?Using dataframe.apply() functionUsing lambda function along with the apply() functionUsing dataframe.transform() functionUsing map() functionUsing NumPy.square() function We make use of the Pandas dataframe to store data in an organized and tabular manner. Sometimes there, is a need to apply a function over a specific column […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.