No conversion from RGB to YUV

11,123

Solution 1

you could try 'YCbCr' instead of 'YUV', i.e.

from PIL import Image
img = Image.open('test.jpeg')
img_yuv = img.convert('YCbCr')

Solution 2

You can try this:

import cv2
img_yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)

Solution 3

I know it may be late, but scikit-image has the function rgb2yuv

from PIL import Image
from skimage.color import rgb2yuv

img = Image.open('test.jpeg')
img_yuv = rgb2yuv(img)    

Solution 4

If you don't want to install any additional package, you can just take a look at skimage source code. The following snippet is taken from that github page with some minor changes:

# Conversion matrix from rgb to yuv, transpose matrix is used to convert from yuv to rgb
yuv_from_rgb = np.array([[ 0.299     ,  0.587     ,  0.114      ],
                     [-0.14714119, -0.28886916,  0.43601035 ],
                     [ 0.61497538, -0.51496512, -0.10001026 ]])

# Optional. The next two line can be ignored if the image is already in normalized numpy array.
# convert image array to numpy array and normalize it from 0-255 to 0-1 range
new_img = np.asanyarray(your_img)
new_img = dtype.img_as_float(new_img)

# do conversion
yuv_img = new_img.dot(yuv_from_rgb.T.copy())
Share:
11,123
romeasy
Author by

romeasy

Updated on June 16, 2022

Comments

  • romeasy
    romeasy about 2 years

    I fail to find an easy-to-use function in any Python library (preferrably PIL) for conversion from RGB to YUV. Since I have to convert many images, I don't want to implement it myself (would be expensive without LUTs and so on).

    When I do the intuitive:

    from PIL import Image
    img = Image.open('test.jpeg')
    img_yuv = img.convert('YUV')
    

    I get an error:

    ValueError: conversion from RGB to YUV not supported
    

    Do you know why this is the case? Is there any efficieint implementation of that in python and maybe even PIL?

    I am no computer vision expert but I thought this ocnversion is standard in most of the libraries...

    Thanks,

    Roman