DEV Community

Cover image for Grayscale Image conversion with Python
petercour
petercour

Posted on

Grayscale Image conversion with Python

You can convert color images to grayscale. Because you have different color channels (R,G,B), you can change how it does that.

The input image is in color, then the program runs, and outputs a gray scale image. I took this input image:

The example below uses OpenCV, a computer vision library for Python. Computer vision goes beyond basic image processing, the computer vision field uses Machine Learning or Deep Learning.

Back to image processing, so all pixels are replaced by itself times an amount.

This way we access the color channel of each pixel, where (i,j) are the coordinates

image[i,j][0] 
image[i,j][1]
image[i,j][2]

Then in code:

#!/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.

Related links:

Top comments (0)