cv2.cvtColor() method converts the color space of an image. This function accepts two arguments:
cv2.cvtColor(image, flag)
cv2.COLOR_CURRENT2NEW
Here, CURRENT refers to the current color space. NEW points to the new color space.
For example, if you want to convert a BGR image to a grayscale, the flag will be cv2.COLOR_BGR2GRAY
.
There are various flags that you can pass to the cv2.cvtColor() method, but in this tutorial, commonly used flags are explained below:
cv2.COLOR_BGR2RGB: This flag converts BGR color space to RGB color space.
cv2.COLOR_BGR2GRAY: This flag converts a BGR image to grayscale.
cv2.COLOR_BGR2HSV: If you want to convert a BGR image to HSV, then use this flag.
cv2.COLOR_BGRA2RGBA: This flag reverses the channel of an image from BGRA to RGBA.
Let's learn how to use cv2.cvtColor()
method using an example:
Suppose you want to convert JPEG image to grayscale then run the below code:
import cv2 img = cv2.imread('/home/mohit/cardiff.jpg') if img is None: print('Image is not present.') else: img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.imshow(img) cv2.destroyAllWindows() cv2.waitKey(0)
Output