0

I want to convert a color image to grayscale using Python. All the tutorials regarding this implement this using OpenCV, whereas I want to do this without the help of any library.

Here's how I implement this using OpenCV:

import numpy as np
import cv2

img = cv2.imread("input.jpg", 0)
cv2.imwrite("output.jpg", img)

Can this be implemented using pure Python?

Talha Quddoos
  • 556
  • 6
  • 17
  • 2
    `Grayscale` is just a weighted average between the three channels `RGB`. Extract every `RGB` pixel on the original image and apply the [conversion formula](https://mmuratarat.github.io/2020-05-13/rgb_to_grayscale_formulas). For example: _Y = 0.299 × R + 0.587 × G + 0.114 × B_. The values of the weights depend on the model you use to convert to `Grayscale`. – stateMachine May 13 '21 at 06:04

1 Answers1

3

You could write it, based on the conversion formula "Standard" RGB to Grayscale Conversion:

import numpy as np

def rgb2gray(rgb):

    r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]
    gray = 0.2989 * r + 0.5870 * g + 0.1140 * b

    return gray
David
  • 8,113
  • 2
  • 17
  • 36