The most optimal way to convert any input image into grayscale is using the OpenCV library’s cv2.cvtColor() method. First, you read a method using cv2.imread(), then convert it to grayscale, and save it to the local file system using cv2.imwrite().
If you convert an image to grayscale, it transforms a color image into a single-channel image where each pixel represents a shade of gray, typically ranging from black (0) to white (255).
The figure above shows the image before and after conversion to grayscale.
OpenCV reads images in BGR format.
Here is the input image we will use for this tutorial:

import cv2
# Read image (OpenCV uses BGR format)
bgr_image = cv2.imread("sample_image.png")
# Convert to grayscale
gray_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2GRAY)
# Save result
cv2.imwrite("gray_opencv.jpg", gray_image)
cv2.imshow('Original', bgr_image)
cv2.imshow('Grayscale', gray_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Already Grayscale?
What if an input image is already a grayscale image? How will you deal with that?
You can compare the input image’s shape = 2, and if it does, it is already grayscaled; otherwise, it is not.
import cv2
# Read the image
image = cv2.imread("gray_opencv.jpg")
# Check if image was loaded successfully
if image is None:
print("Error: Image not found or cannot be opened.")
else:
# Check if image is already grayscale
if len(image.shape) == 2 or (len(image.shape) == 3 and image.shape[2] == 1):
gray_image = image
else:
# Convert to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Display the grayscale image
cv2.imshow('Grayscale', gray_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
It is the best approach if you are already using the OpenCV library for computer vision tasks.
Using Pillow
Pillow is a third-party image processing library that provides a .convert(“L”) method that converts an input image into a grayscale image.
from PIL import Image
img = Image.open("sample_image.png")
# Convert to grayscale
gray_img_pil = img.convert("L") # 'L' mode = luminance
# Save the grayscale image
gray_img_pil.save("gray_pillow.jpg")
# Display the grayscale image
gray_img_pil.show()
The .convert(‘L’) method uses 8-bit pixels, black and white. It is portable, lightweight, and works with many formats (JPEG, PNG, etc.).
That’s all!




