Last modified: Nov 15, 2023 By Alexander Williams
Python: Grayscale Conversion of Images - Examples
Example 1: Grayscale Conversion using OpenCV
import cv2
# Read the image
image = cv2.imread('path/to/your/image.jpg')
# Convert the image to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
Output:
# Display the grayscale image
Example 2: Grayscale Conversion using Pillow
from PIL import Image
# Open the image
image = Image.open('path/to/your/image.jpg')
# Convert the image to grayscale
gray_image = image.convert('L')
Output:
# Display the grayscale image (if needed)
Example 3: Grayscale Conversion using NumPy
import cv2
import numpy as np
# Read the image
image = cv2.imread('path/to/your/image.jpg')
# Convert the image to grayscale using NumPy
gray_image = np.dot(image[...,:3], [0.299, 0.587, 0.114])
Output:
# Display the grayscale image
Example 4: Grayscale Conversion using scikit-image
from skimage import io, color
# Read the image
image = io.imread('path/to/your/image.jpg')
# Convert the image to grayscale using scikit-image
gray_image = color.rgb2gray(image)
Output:
# Display the grayscale image (if needed)
Example 5: Grayscale Conversion using imageio
import imageio
# Read the image
image = imageio.imread('path/to/your/image.jpg')
# Convert the image to grayscale using imageio
gray_image = imageio.plugins.color.rgb2gray(image)
Output:
# Display the grayscale image (if needed)