0

Can anyone help me to convert an RGB colour space image to YUV colour space image and to YCbCr colour space image using opencv Python?

1 Answers1

11

Use cv2.cvtColor(src, code) to convert Color-Space, the code starts with COLOR_.

You can use this to look for the color code.

import cv2
## get all color codes
codes = [x for x in dir(cv2) if x.startswith("COLOR_")]

## print first three color codes
print(codes[:3])
# ['COLOR_BAYER_BG2BGR', 'COLOR_BAYER_BG2BGRA', 'COLOR_BAYER_BG2BGR_EA']

## print all color codes
print(codes)

If you read the image into BGR space, then use cv2.COLOR_BGR2YUV and cv2.COLOR_BGR2YCrCb:

#cv2.COLOR_BGR2YUV
#cv2.COLOR_BGR2YCrCb

img = cv2.imread("test.png")
yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
cv2.imwrite("yuv.png", yuv)

If you read the image into RGB space, then use cv2.COLOR_RGB2YUV and cv2.COLOR_RGB2YCrCb.


Here is an example image(in BGR-HSV-YUV-YCRCB color spaces):

enter image description here

Alex Cohn
  • 56,089
  • 9
  • 113
  • 307
Kinght 金
  • 17,681
  • 4
  • 60
  • 74
  • 1
    Note that `cv2.COLOR_RGB2YCrCb` produces a 3D array, while reslut of `cv2.COLOR_BGR2YUV_YV12` is a 2D array with same height (`im.shape[0] == h`), but extra width (`im.shape[1] == w*3/2`), and *chroma* info (**U** and **V**) are stored there interlaced. Also, the numerical values are different for YUV and YCrCb: for the former, *luminance* is between **16** to **235**, as expected for [some video gamuts](https://en.wikipedia.org/wiki/Rec._709), while YCrCb is full **0..255** range. – Alex Cohn Oct 29 '18 at 14:10
  • @AlexCohn Instead of cv2.COLOR_BGR2YUV_YV12 is there a conversion code for YCrCb 420 format? I couldn't find it in the documentation – Shravya Boggarapu Feb 18 '19 at 05:43
  • @ShravyaBoggarapu I am not sure I understand your question. What is your input format, and what do you need on output? – Alex Cohn Feb 18 '19 at 15:19
  • @AlexCohn, YUV uses only video range (16-235) but YCrCb uses the full pixel range, right? but it is always present in 444 format (1: 1: 1 for the 3 components) but 420 format is such that the chroma components are quarter the size of luma component. OpenCV provides means to convert to YUV420 (video range) but not full range- as far as I could find. I was wondering if you knew – Shravya Boggarapu Mar 07 '19 at 14:06