How to convert an image to a greyscale image with Python and OpenCV
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
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 ): print "File not found" sys.exit( -1 ) filename = sys.argv
With sys.argv we can receive parameters from command line. The first parameter sys.argv 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).
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: