How to convert an image to a greyscale image with Python and OpenCV

Categories: Computer-Vision, Tutorials

In this tutorial I will show you how to use OpenCV with Python. OpenCV is a Computer-Vision-Library which was developed by Intel and is now developed by WillowGarage.

Installing Python and OpenCV

Windows: Download Python 2.7 from here and install it. You can download precompiled OpenCV-bindings for windows here. If you want to install it manually, have a look at this.

Linux: Just install the packages for your distribution. E.g. for Ubuntu:

sudo apt-get install python python-opencv

Writing the script

Now we want to create a script that reads an image and converts it to a greyscale image. So we start our script with receiving a filename from command line:


import cv2
import sys
import os

if len( sys.argv )
    print "Usage: greyscale Path/to/Image"
    sys.exit( -1 )
elif not os.path.exists( sys.argv[1] ):
    print "File not found"
    sys.exit( -1 )

filename = sys.argv[1]

With sys.argv we can receive parameters from command line. The first parameter sys.argv[0] is always the name of the script. So we have to check if there is another parameter and if that file really exists. This is done with os.path.exists(sys.argv[1]).

After we are sure, that the file exists, we want to read it and save it in a variable called img:

img = cv2.imread( filename )

The variable img contains our image now. So we can go on and use some of the features OpenCV offers. Before we can apply a threshold we have to convert our image from RGB to GRAY. Therefore we use the function cvtColor. This function converts an image img into the given colorspace. As we want a greyscale image we use cv2.COLOR_RGB2GRAY:

img = cv2.cvtColor( img, cv2.COLOR_RGB2GRAY )

Now img contains a grayscale-image. Finally we write that new image to a file called grey.png:

cv2.imwrite( "grey.png", img )

Thats all. Now run the script with:


python greyscale.py YOUR_IMAGE

Running the script will create a file called grey.png in the folder your script is executed.

You can download the full script here:

One comment on “How to convert an image to a greyscale image with Python and OpenCV”

  1. Thomas says:

    Thank you, it works!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>