Image Effects A Guide to Adding Text to Images with Python A Guide to Converting Images to Grayscale with Python Introduction Creating an Image Overlay with JavaScript Rotating an Image in Python Creating a Dynamic Photo Gallery with jQuery Creating An Interactive Photo Gallery Using JavaScript Mastering Overlay in Android Mastering Angular Overlay: A Comprehensive Guide Comprehensive Guide to Overlay in Flutter Mastering Overlay React for Responsive Design Solutions Create a Blurred Image with PHP: A Comprehensive Guide Guide to Using Blur Image in Flutter Mastering Blur Image in React Native Mastering Image Blurring in Python Mastering the Art of Image Blurring Mastering the Art of Image Blurring in Java The Ultimate Guide to Blurring Images on Android Understanding and Implementing Blur Image in JQuery An Extensive Walkthrough of Blurring Images with JavaScript How to Use HTML, CSS, and JavaScript to Make an Image Slider HTML Image Tag How to Crop GIFs? How to Align Images with CSS Ken Burns Effect – Complete Guide and How to Apply It Cartoonify – Complete Guide on Cartoonify Image Effect Mastering Web Aesthetics: A Comprehensive Guide to Gradient Fades Sepia Effect: The Ultimate Guide to the Sepia Photo Effect What is Vignette? Guide to Vignette Image Editing Pixelate – The Ultimate Guide to the Pixelation Effect How to Outline an Image: Enhancing Visual Appeal and Depth Make Your Photos Pop with Image Effects Upscale Image – Developers guide to AI-driven image upscaling Image Manipulation: History, Concepts and a Complete Guide A Full Guide to Object-aware Cropping Simplify Your Life with Automatic Image Tagging How To Resize Images In WordPress How To Create a Progress Bar For Asset Uploads Animated GIFs – What They Are And How To Create Them How To Automatically Improve Image Resolution AI Drop Shadow Get Image Dimensions From URLs Automatically Add Sepia Effect To Images Automatically Make an Image a Cartoon Automatically Add Blur Faces Effect To Images Automatically Add Background Removal Effect to an Image How to Resize an Image with React How to Easily Resize an Image with React Native

A Guide to Converting Images to Grayscale with Python Introduction

grayscale images python

Grayscale images, also known as black-and-white or monochrome images, are images with shades of gray from black to white, with each pixel having a single intensity value. Grayscale images are widely used in various applications such as image enhancement, compression, and feature extraction. Below is an example of a grayscale image:

grayscale images python
Image Credits: Jocelyn Morales on Unsplash

There are extensive libraries and tools in Python for converting colored images into grayscale. Examples include PIL (Python Imaging Library), OpenCV, and so on. In this guide, we’ll explore some popular libraries and approaches for converting images to grayscale in Python.

Using the Pillow Library

Pillow is a fork of PIL (Python Imaging Library) with a robust tool-set for image processing in Python. It provides a wide range of functions for loading, manipulating, and saving images in various formats.

Here’s an example of how to convert an image to grayscale using Pillow:

from PIL import Image

# Open the image
image = Image.open("nature.png")

# Convert the image to grayscale. The `"L"` argument in Pillow represents grayscale mode.
grayscale_image = image.convert("L")

# Save the grayscale image
grayscale_image.save("grayscale_image.jpg")

Here’s the input nature.png file we want to convert to grayscale:

grayscale images python

And here’s the output after we converted it to grayscale:

grayscale images python

Using OpenCV

OpenCV (Open Source Computer Vision Library) is a free, cross-platform, and open-source library for computer vision and various image processing tasks. It provides many functions for reading, writing, and manipulating images.

Here’s how we can use OpenCV to convert images to grayscale in Python:

import cv2 
# Load the image 
image = cv2.imread("input_image.jpg") 

# Convert the image to grayscale
grayscale_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 

# Save the grayscale image 
cv2.imwrite("grayscale_image.jpg", grayscale_image)

We can use several other methods and libraries for grayscale conversion in Python. Examples include Scikit-py and Mahotas, and the list goes on and on.

grayscale images python

Converting Images to Grayscale with Cloudinary

Cloudinary is a cloud-based media management platform that simplifies the process of storing, managing, and delivering digital media assets such as images and videos. One of the key features of Cloudinary is its support for on-the-fly image manipulation.

Grayscale conversion is one of the many image manipulation features supported in Cloudinary. Compared to other solutions, it’s simple and efficient to implement. Let’s look at the two approaches for applying the grayscale effect to images with Cloudinary.

Applying Grayscale Transformation to URLs

The first method directly applies the transformation parameter to the image URL. For example, suppose you have an image uploaded to Cloudinary with the following URL:

https://res.cloudinary.com/demo/image/upload/happy_dog.jpg

We can simply tweak the URL by adding e_grayscale to apply the grayscale effect as follows:

python3 -m pip install fastapi python-multipart cloudinary 
pydantic-settings python-dotenv uvicorn[standard]

Below is the complete code for the application:

# main.py
from fastapi import FastAPI
from fastapi import FastAPI, File, UploadFile
from pydantic_settings import BaseSettings
import cloudinary
import os

class Settings(BaseSettings):
    CLOUDINARY_CLOUD_NAME: str
    CLOUDINARY_API_KEY: int
    CLOUDINARY_API_SECRET: str
    class Config:
        env_file = ".env"    

settings = Settings()

config = cloudinary.config(cloud_name = settings.CLOUDINARY_CLOUD_NAME, api_key = settings.CLOUDINARY_API_KEY, api_secret = settings.CLOUDINARY_API_SECRET)

import cloudinary.uploader
import cloudinary.api

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

The above code imports a few libraries to configure the application. We also defined a class to load the environment variables containing our Cloudinary credentials.
We can now create an endpoint to upload an image to Cloudinary and convert it to grayscale.

# main.py
async def cloudinary_upload(file):
    grayscale_image =  cloudinary.uploader.upload(file, effect="grayscale")
    return grayscale_image

@app.post("/upload")
async def create_image(image: UploadFile = File(...)):
    os.makedirs("images", exist_ok=True)
    # Here we save the image to disk so we can upload it to Cloudinary
    file_location = f"images/{image.filename}"
    with open(file_location, "wb+") as file_object:
        file_object.write(image.file.read())

    result = await cloudinary_upload(file_location)


    grayscale_img = result["secure_url"]


    return f"The converted image can be found here: {grayscale_img}"

Now, uploading the same image from the previous example to our application returns the following URL:

https://res.cloudinary.com/cloudinarymich/image/upload/v1712034063/fkijrxyw8npa86y27lxg.jpg

Here’s the output in the browser:

grayscale images python

Wrapping Up

In this article, we explored different methods of adding grayscale effects to images in Python. We explored popular options such as Pillow, OpenCV, and Cloudinary. We also saw how Cloudinary compares to the other methods in simplicity and efficiency.

Transform and optimize your images and videos effortlessly with Cloudinary’s cloud-based solutions. Sign up for free today!

Last updated: Apr 21, 2024