How about doing it with Pillow:

from PIL import Image
img = Image.open('image.png').convert('L')
img.save('greyscale.png')

If an alpha (transparency) channel is present in the input image and should be preserved, use mode LA:

img = Image.open('image.png').convert('LA')

Using matplotlib and the formula

Y' = 0.2989 R + 0.5870 G + 0.1140 B 

you could do:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

def rgb2gray(rgb):
    return np.dot(rgb[...,:3], [0.2989, 0.5870, 0.1140])

img = mpimg.imread('image.png')     
gray = rgb2gray(img)    
plt.imshow(gray, cmap=plt.get_cmap('gray'), vmin=0, vmax=1)
plt.show()
Answer from unutbu on Stack Overflow
🌐
Cloudinary
cloudinary.com › home › a guide to converting images to grayscale with python introduction
A Guide to Converting Images to Grayscale with Python Introduction | Cloudinary
April 21, 2024 - 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.
Discussions

How do I convert from grayscale to black and white?
In Python the PIL images directly support converting to grayscale or pure black and white. Have a Look at the stackoverflow link below. The first answer uses a default transformation to black and white and the 2nd answer uses a custom threshold https://stackoverflow.com/questions/9506841/using-pil-to-turn-a-rgb-image-into-a-pure-black-and-white-image More on reddit.com
🌐 r/learnpython
5
1
September 24, 2023
Converting RGBA image to Gray scale and then binary
Hi, I need to convert a RGBA image in to Gray scale and then to binary with a threshold but I am not able to do that in python. Here is my code . The error which I get is “AttributeError: module ‘PIL.Image’ has no attribute ‘rgb2gray’” # Import libraries from PIL import Image import ... More on discuss.python.org
🌐 discuss.python.org
6
0
August 21, 2021
Convert RGB Image to Grayscale and Display It (Python + Matplotlib) - Signal Processing Stack Exchange
I just started learning image processing and I was trying to read a RGB image then convert it to grayscale. I was hoping for something like this: However, what I get was: I tried using both scipy a... More on dsp.stackexchange.com
🌐 dsp.stackexchange.com
Converting an RGB image to grayscale and manipulating the pixel data in python - Stack Overflow
I have an RGB image which I want to convert to a grayscale image, so that I can have one number (maybe between 0 and 1) for each pixel. This gives me a matrix which has the dimensions equal to that... More on stackoverflow.com
🌐 stackoverflow.com
March 11, 2016
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-grayscaling-of-images-using-opencv
Python | Grayscaling of Images using OpenCV - GeeksforGeeks
September 23, 2025 - In this method, we can directly load an image in grayscale mode by passing the flag 0 to cv2.imread(). This saves us from having to convert the image separately after loading.
🌐
techtutorialsx
techtutorialsx.wordpress.com › 2018 › 06 › 02 › python-opencv-converting-an-image-to-gray-scale
Python OpenCV: Converting an image to gray scale – techtutorialsx
January 25, 2025 - You also need to install Numpy, which can be done with pip, the Python package manager, by sending the following command on the command line: ... To get started, we need to import the cv2 module, which will make available the functionalities ...
🌐
Delft Stack
delftstack.com › home › howto › python › convert image to grayscale python
How to Convert Image to Grayscale in Python | Delft Stack
February 2, 2024 - The below example code demonstrates ... using the standard RGB to grayscale conversion formula that is imgGray = 0.2989 * R + 0.5870 * G + 0.1140 * B....
🌐
Medium
medium.com › @nutanbhogendrasharma › convert-a-color-image-to-gray-scale-in-python-7fe952934c0a
Convert a Color Image to Gray Scale in Python | by Nutan | Medium
July 27, 2023 - Convert a Color Image to Gray Scale in Python In this blog, we will convert color images into grayscale using the Pillow and CV2 packages. Installation We will use opencv-python and the pillow module …
🌐
MLK
machinelearningknowledge.ai › home › 8 ways to convert image to grayscale in python using skimage, pillow, opencv, numpy, matplotlib, imageio
8 Ways to Convert Image to Grayscale in Python using Skimage, Pillow, OpenCV, Numpy, Matplotlib, ImageIO - MLK - Machine Learning Knowledge
January 18, 2024 - Scikit Image or Skimage is a Python based open-source package for various image processing algorithms. Any color image can be converted to grayscale with the help of color.rgb2gray() function of Skimage.
Find elsewhere
🌐
scikit-image
scikit-image.org › docs › dev › auto_examples › color_exposure › plot_rgb_to_gray.html
RGB to grayscale — skimage 0.26.1rc0.dev0 documentation
import matplotlib.pyplot as plt from skimage import data from skimage.color import rgb2gray original = data.astronaut() grayscale = rgb2gray(original) fig, axes = plt.subplots(1, 2, figsize=(8, 4)) ax = axes.ravel() ax[0].imshow(original) ax[0].set_title("Original") ax[1].imshow(grayscale, cmap=plt.cm.gray) ax[1].set_title("Grayscale") fig.tight_layout() plt.show()
🌐
TutorialsPoint
tutorialspoint.com › python-grayscaling-of-images-using-opencv
Python Grayscaling of Images using OpenCV
November 13, 2024 - Manual Averaging refers to, calculating the grayscale value by taking the average of the B, G, and R channels for each pixel. import cv2 import numpy as np # Read the image image = cv2.imread('apple.jpg') # Manually convert to grayscale using the average method gray_image = np.zeros(image.shape[:2], dtype='uint8') for i in range(image.shape[0]): for j in range(image.shape[1]): # Calculate the average of the B, G, R values gray_image[i, j] = np.mean(image[i, j]) # Display the grayscale image cv2.imshow('Grayscale Image', gray_image) cv2.waitKey(0) cv2.destroyAllWindows()
🌐
Medium
medium.com › @bulanlobo_priestly › convert-rgb-image-to-grayscale-image-manually-without-any-library-ea92bf0e5295
Convert RGB Image to Grayscale Image Manually without Any Library | by priestly bulan lobo | Medium
November 4, 2024 - # Declare method for convert image ... = np.zeros((height, width), dtype=np.uint8) # Convert to grayscale using (R+G+B)/3 for i in range(height): for j in range(width): gray_...
🌐
AskPython
askpython.com › home › convert an rgb image into grayscale using matplotlib
Convert an RGB image into grayscale using Matplotlib - AskPython
February 16, 2023 - Using Scikit Learn to Grayscale Images. This tutorial covers the basic image manipulation techniques involving matplotlib, NumPy and scikit learn. Converting a colored image into black and white can be useful on many occasions to reduce the size of a program and remove unnecessary pixel data. You can learn more about image processing using python here further.
🌐
scikit-image
scikit-image.org › docs › stable › auto_examples › color_exposure › plot_rgb_to_gray.html
RGB to grayscale — skimage 0.26.0 documentation
import matplotlib.pyplot as plt from skimage import data from skimage.color import rgb2gray original = data.astronaut() grayscale = rgb2gray(original) fig, axes = plt.subplots(1, 2, figsize=(8, 4)) ax = axes.ravel() ax[0].imshow(original) ax[0].set_title("Original") ax[1].imshow(grayscale, cmap=plt.cm.gray) ax[1].set_title("Grayscale") fig.tight_layout() plt.show()
🌐
Reddit
reddit.com › r/learnpython › how do i convert from grayscale to black and white?
r/learnpython on Reddit: How do I convert from grayscale to black and white?
September 24, 2023 -

Consider the following image:

Image

If you zoom in, you will observe that the picture contains pixels of the form (0,0,0,x) in RGBA format (I have used pillow to verify this btw). What I want to do is if the pixel's alpha is less than equal to 200, then write (0,0,0,0) at the pixel's place, and if it is greater than 200 then write (0,0,0,255) at the pixel's place.

Here's my code rn:

from PIL import Image
import numpy as np

def inp_gen(img_path):
    im = Image.open(img_path, 'r')
    pix_vals = list(im.getdata())
    layer = [x[3] for x in pix_vals]
    for j in layer:
        if j <= 200:
            layer[layer.index(j)] = 0
        if j > 200:
            layer[layer.index(j)] = 1 
    return layer

def render_img(img_data):
    image_data = [(0,0,0,255*x) for x in img_data]
    data = np.array(image_data, dtype=np.uint8).T
    image = Image.fromarray(data)
    image.show() 

render_img(img_gen("Path to image in drive link on my PC"))

Sadly, this does not give me the output I want:

Output

So what should I do now?

🌐
Python.org
discuss.python.org › python help
Converting RGBA image to Gray scale and then binary - Python Help - Discussions on Python.org
August 21, 2021 - Hi, I need to convert a RGBA image in to Gray scale and then to binary with a threshold but I am not able to do that in python. Here is my code . The error which I get is “AttributeError: module ‘PIL.Image’ has no attribute ‘rgb2gray’” # Import libraries from PIL import Image import matplotlib.pyplot as plt import numpy as np # Reading an Image image = Image.open('Board1_1.png') image_gray = Image.rgb2gray(image)
🌐
DEV Community
dev.to › petercour › grayscale-image-conversion-with-python-50ho
Grayscale Image conversion with Python - DEV Community
July 17, 2019 - #!/usr/bin/python3 import cv2 image = cv2.imread('image.jpg') grayimg = image height, width, channels = image.shape for i in range(height): for j in range(width): grayimg[i,j] = 0.3 * image[i,j][0] + 0.59 * image[i,j][1] + 0.11 * image[i,j][2] cv2.imshow('srcImage', image) cv2.imshow('grayImage', grayimg) cv2.waitKey(0) By changing the values you can create different grayscale images: So color to gray conversion can create very different images, based on which color channels you emphasize.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-pil-imageops-greyscale-method
Python PIL | ImageOps.grayscale() method - GeeksforGeeks
October 27, 2021 - Syntax: PIL.ImageOps.grayscale(image) Parameters: image – The image to convert into grayscale. Returns An image.
🌐
HolyPython
holypython.com › home › python pil tutorial › how to convert an image to black & white in python (pil)
How to convert an image to Black & White in Python (PIL) | HolyPython.com
December 10, 2022 - In this Python Tutorial, we have covered B&W and grayscale conversions in depth. Namely we have used; Image module’s .convert() and ImageEnhance module’s .Color methods.
🌐
Java2Blog
java2blog.com › home › python › convert image to grayscale in python
Convert image to grayscale in python - Java2Blog
August 20, 2021 - 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.