Do you want to convert an image into different colors in python? Then there is a function in OpenCV that allows you to do so and it is cv2 cvtColor. In this entire tutorial, you will know how to implement cv2 cvtcolor in python through steps.
Steps to Implement cv2 cvtColor
In this section, you will know all the steps required for converting an image to a different color.
Step 1: Import the necessary libraries
In my example, I am using only OpenCV that why I will import it only using the import statement.
If you have not installed OpenCV in your system. Then read how to install opencv using pip.
Step 2: Read the sample image
The second step is to read the input image for conversion. In OpenCV, you can read images using imread() method. Let’s read the image.
img = cv2.imread("bird.jpg")
Below is the image I am using.
Step 3: Convert the image
In this step let’s convert the input image to different colors. There are more than 150 color-space conversion methods available in OpenCV. In this tutorial, I am converting the BGR image to gray and HSV. The following is the syntax for the cv2.cvtColor().
Here the input_image is the image you want to convert. And the flag is the type of conversion. You can know all the flags using the following code.
import cv2 flags = [i for i in dir(cv2) if i.startswith('COLOR_')] print flags
Convert image to Gray
You can convert any image to gray by passing the flag as cv2.RGB2GRAY. Use the below lines of code to convert the colored image to Gray.
import cv2 img = cv2.imread("bird.jpg") grey_image = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) cv2.imshow("Gray Image of Bird",grey_image) cv2.waitKey(0)
To show the image you will use imshow() method provided by OpenCV. Below is the output you will get when you will run the above code.
Converting image to HSV
HSV is a cylindrical color model that remaps the RGB primary colors. If you will pass cv2.RGB2HSV inside the cv2.cvtColor() then you will get the image in HSV color. Execute the below lines of code and see the output.
import cv2 img = cv2.imread("bird.jpg") grey_image = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) hsv_image = cv2.cvtColor(img,cv2.COLOR_BGR2HSV) cv2.imshow("HSV Image of Bird",hsv_image) cv2.waitKey(0)
These are the steps to implement cv2 cvtColor. I have given two colors examples for this method. But there are also other colors you can convert using this method. Hope you have liked this tutorial. If you have any queries then you can contact us for more help.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.