Python | cv2 cvtColor() Method

In this tutorial, we will see how to change the color of an image from one color space to another using python open-cv, which exists as cv2 (computer vision) library.

You can use cvtColor() method of cv2 library to convert the color of an image from one color space to another. To use cv2 library, you need to import cv2 library using import statement.

There are more than 150 shading space transformation techniques accessible in OpenCV. In any case, we will investigate just two which are most broadly utilized ones, BGR Gray and BGR HSV.

BGR –> Blue Green Red
HSV –> Hue Saturation Values

Note :
1) For BGR, Blue,Green,Red value range is [0,255]
2) For HSV, Hue range is [0,179], Saturation range is [0,255] and Value range is [0,255].

Now let’s see the syntax and return value of cv2 cvtColor() the method first, then we will move on to the examples.



You can pass four parameters to cvtColor() method. Among the four parameters, the first 2(image and code) are mandatory; rest(dst and dstCn) are optional.

    1. Necessary parameters are:

    2. image: Source/Input image of n-dimensional array.
    3. code: Conversion code for color space.

Optional parameters are:

  1. dst: Output image of the same size and depth as source.
  2. dstCn: The number of channels in the destination image. If you put parameter as 0, the number of the channels is obtained automatically from image and code.

Return Value :

It returns the Coverted color space image.

The default color format in OpenCV is often referred to as RGB, but it is actually BGR (the bytes are reversed). So the first byte in a standard (24-bit) color image will be an 8-bit Blue component, the second byte will be Green, and the third byte will be Red. The fourth, fifth, and sixth bytes would then be the second pixel (Blue, then Green, then Red), and so on.

cv2 cvtColor() Method examples

Now Let’s see the Python code :

Example 1: Convert image from BGR color space to GRAY color space.


Example 2: Convert image from BGR color space to HSV color space.


That’s all about Python cv2 cvtColor() Method.

Related Posts

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.