Hey guys, been reading OpenCV for python and thought of posting a tutorial on Programming a Grayscale Image Convertor. I encourage you to google them , there are lots and lots of examples and code snippets. This is on how to a convert any image to gray scale using Python and OpenCV.
A sample input image and output image are shown below (YEah, I am big Iron Man Fan! :B). You can click on image to enlarge:
I have placed an image named “ironman.png” in the current working directory (i.e. I have the original image in the same directory as the place where I have saved my Python code).
First we import the cv2 module:
Then ,read the image to a variable named “image” :
image = cv2.imread('ironman.png')
Now, to convert to gray-scale image and store it to another variable named “gray_image” use the function cv2.cvtColor() with parameters as the “image” variable and “cv2.COLOR_BGR2GRAY” :
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
So, now the variable “gray_image” will hold the gray-scale version of the input image.
Now, to write/save the converted gray-scale image to the hard disk, we use the function “cv2.imwrite()” with parameters as “the name of converted image” and the variable “gray_image” to which the converted image was stored:
So, now if you open the directory where you saved your python code, you can see a new image there : gray_image.png! Wow! :D
Now, to display the original and the gray-scale ,we use function “cv2.imshow()” with parameters as the “window title” and the “image variable” :
Complete Code for GrayScale Image convertor:
# GrayScale Image Convertor # https://extr3metech.wordpress.com import cv2 image = cv2.imread('ironman.png') gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imwrite('gray_image.png',gray_image) cv2.imshow('color_image',image) cv2.imshow('gray_image',gray_image) cv2.waitKey(0) # Waits forever for user to press any key cv2.destroyAllWindows() # Closes displayed windows #End of Code
Hope you enjoyed this post, feel free to comment and don’t forget to follow my blog! :D