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
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 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
Converting Grayscale to Color Image using Color Maps
Mathematically, you can't. Grayscale has 0-255 values. RGB has 256x256x256. The only way to map something is to use external information. For example, if your scene has sky, you can assume that a grayscale value where the sky is maps to a blue-ish tone. That would help resolve some ambiguity elsewhere. This is what AI does to re-colorize photographs. It makes guesses on pixel colors based on the structure of the image, which it learns from training. It can make mistakes. You can reverse calculate if you want. There is a formula to convert RGB to grayscale (easy to find on the internet). So from there, you can see where the same grayscale value will revert to two or more RGB values. Same goes with other colorspaces that use more than one channel to define a color. Edit: Looking at your other post, you seem to not really need accuracy, just straight conversion from 0-255 to whatever colormap you need. In this case, my answer above is not applicable (but keeping it here for other info on a general grayscale to RGB attempt). If the colormap are neighbors in the colorwheel (e.g., the H in HSV), you could try a basic ratio and proportion using the grayscale and pick the color from the H range. More on reddit.com
🌐 r/learnpython
3
2
February 11, 2024
🌐
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.
🌐
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....
🌐
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 ...
🌐
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 …
🌐
YouTube
youtube.com › watch
Convert An Image To Grayscale Using Python - YouTube
Learn how to convert a given image into black and white or say gray scale image. You can also use this trick to create a sketch of a person. Don't wait and t...
Published   September 13, 2022
Find elsewhere
🌐
Data Science Learner
datasciencelearner.com › python › convert-image-to-grayscale-python
How to Convert Image to Grayscale in Python : 3 Methods
September 18, 2023 - The third method to do the conversion is the use of OpenCV. Here again, I will first load the image and convert the image to grayscale in python using the cvtColor() function. Lastly, I will save the image to the disk using cv2.
🌐
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.
🌐
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()
🌐
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.
🌐
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?

🌐
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()
🌐
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_...
🌐
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.
🌐
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)
🌐
Moonbooks
moonbooks.org › Articles › How-to-convert-an-image-to-grayscale-using-python-
How to convert an image to grayscale using python ?
February 19, 2019 - Note: the conversion to grayscale is not unique see l'article de wikipedia's article). It is also possible to convert an image to grayscale and change the relative weights on RGB colors, example:
🌐
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.