O'Reilly logo

Computer Vision with Python 3 by Saurabh Kapur

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Changing the color space

OpenCV provides the cvtColor() function to convert the image from one color space to another. It takes the image as input and also the color space conversion code. The following are a few conversion codes:

  • COLOR_BGR2GRAY
  • COLOR_BGR2HSV
  • COLOR_HSV2BGR
  • COLOR_BGR2YUV
  • COLOR_GRAY2BGR 

The following is an example code for converting a BGR image to a grayscale image. We can change the second parameter of the cvtColor() function by any of the earlier mentioned parameter values:

>>> import cv2>>> img = cv2.imread("image.jpg")>>> gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)>>> cv2.imwrite("gray_image.jpg", gray)>>> cv2.imshow("image",gray)

The following figure is the output of the preceding code:

Figure 2: The original image ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required