Rate This Document
Findability
Accuracy
Completeness
Readability

cvtColor

Usage

Converts image color space from one format to another, for example, from BGR (default) to grayscale, RGB, or another. This is important for image processing and computer vision tasks because each color space has unique advantages in specific applications.

Interface

1
cv2.cvtColor(src, code, dst=None, dstCn=0)

Parameters

Parameter

Description

Value Range

Input/Output

src

Input image.

Not null

Input

code

Color conversion code used to specify the conversion type, such as cv2.COLOR_BGR2GRAY, cv2.COLOR_BGR2RGB, cv2.COLOR_RGB2BGR, and cv2.COLOR_GRAY2BGR.

cv2.COLOR_BGR2GRAY, cv2.COLOR_BGR2RGB, cv2.COLOR_RGB2BGR, cv2.COLOR_GRAY2BGR

Input

dst

(Optional) Output image. A new image is created by default.

Not null

Output

dstCn

Number of channels of the output image. The default value is 0, indicating that dstCn is automatically determined according to the color conversion code.

{0, 1, 2, 3, 4}

Input

Return Values

  • Success: KP_CV_SUCCESS
  • Failure: an error code

Error Codes

Error Code

Description

INVALID_PARAM_MSG

The src parameter has a null pointer.

NOT_SUPPORT_MSG

The input image is not of the uint8 type or is not supported by code.

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import numpy as np 
import cv2

# Load the image.
src = np.array([[0, 0, 0, 0, 0],
                [0, 1, 1, 1, 0],
                [0, 1, 0, 1, 0],
                [0, 1, 1, 1, 0],
                [0, 0, 0, 0, 0]], dtype=np.uint8)
# Convert the image from grayscale to BGR.
dst = cv2.cvtColor(src[..., None], cv2.COLOR_GRAY2BGR)

print(dst)

Output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
[[[1 1 1]
  [1 1 1]
  [1 1 1]
  [0 0 0]
  [0 0 0]]

 [[0 0 0]
  [0 0 0]
  [0 0 0]
  [0 0 0]
  [0 0 0]]

 [[0 0 0]
  [1 1 1]
  [0 0 0]
  [1 1 1]
  [0 0 0]]

 [[0 0 0]
  [0 0 0]
  [0 0 0]
  [0 0 0]
  [0 0 0]]

 [[0 0 0]
  [0 0 0]
  [0 0 0]
  [0 0 0]
  [0 0 0]]]