Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No conversion from RGB to YUV

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

like image 873
romeasy Avatar asked Jun 02 '16 09:06

romeasy


4 Answers

You can try this:

import cv2
img_yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
like image 77
Prasanna Parthasarathy Avatar answered Nov 07 '22 08:11

Prasanna Parthasarathy


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

from PIL import Image
img = Image.open('test.jpeg')
img_yuv = img.convert('YCbCr')
like image 21
helmken Avatar answered Nov 07 '22 08:11

helmken


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)    
like image 22
Cristian Alonso Vallejo Avatar answered Nov 07 '22 09:11

Cristian Alonso Vallejo


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())
like image 3
Nghia Tran Avatar answered Nov 07 '22 09:11

Nghia Tran